c# - 找不到文件时处理 FileContentResult

标签 c# asp.net-mvc-2 azure-blob-storage filecontentresult

我有一个 Controller 操作,它根据容器引用名称(即 blob 中文件的完整路径名)从 azure blob 下载文件。代码看起来像这样:

public FileContentResult GetDocument(String pathName)
{
    try
    {
        Byte[] buffer = BlobStorage.DownloadFile(pathName);
        FileContentResult result = new FileContentResult(buffer, "PDF");
        String[] folders = pathName.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
        // get the last one as actual "file name" based on some convention
        result.FileDownloadName = folders[folders.Length - 1];

        return result;
    }
    catch (Exception ex)
    {
        // log error
    }
    // how to handle if file is not found?
    return new FileContentResult(new byte[] { }, "PDF");
}

BlobStorage 类是我的帮助类,用于从 blob 下载流。

我的问题在代码注释中陈述:找不到文件/流时,我应该如何处理?目前,我正在传递一个空的 PDF 文件,我觉得这不是最好的方式。

最佳答案

在 Web 应用程序中处理 not found 的正确方法是向客户端返回 404 HTTP 状态代码,在 ASP.NET MVC 术语中,这将转换为返回 HttpNotFoundResult。从你的 Controller Action :

return new HttpNotFoundResult();

啊,糟糕,没注意到你还在使用 ASP.NET MVC 2。你可以自己实现它,因为 HttpNotFoundResult 仅在 ASP.NET MVC 3 中引入:

public class HttpNotFoundResult : ActionResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }
        context.HttpContext.Response.StatusCode = 404;
    }
}

关于c# - 找不到文件时处理 FileContentResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6450495/

相关文章:

c# - WebClient CookieContainer 在 .NET 4.0+ 中运行良好,但在早期版本中运行不佳

.net - ASP.Net MVC 2 中的多个环境

azure - 无法将 blob 从一个容器复制到另一个容器

azure - 读取 Azure 存储上的 blob 内容

azure - 使用react-native管理azure blob

c# - 获取当前打开的文档

c# - 反序列化到自定义列表

security - MVC - 设置重定向模式时 CustomErrors 不起作用 =“ResponseRewrite”

c# - Web API 和 Angular 5 token 身份验证 - 登录后获取用户信息

c# - 路线总是去第一个 maproute