找不到文件时处理FileContentResult [英] Handling FileContentResult when file is not found

查看:147
本文介绍了找不到文件时处理FileContentResult的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器操作,该操作基于容器引用名称(即,blob中文件的完整路径名)从azure blob下载文件.代码看起来像这样:

I have a controller action that downloads a file from an azure blob based on the container reference name (i.e. full path name of the file in the blob). The code looks something like this:

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下载流.

The BlobStorage class there is my helper class to download the stream from the blob.

我的问题在代码注释中说明:找不到文件/流时,我应该如何处理该方案?目前,我正在传递一个空的PDF文件,我认为这不是最好的处理方法.

My question is stated in the code comment: How should I handle the scenario when the file/stream is not found? Currently, I am passing an empty PDF file, which I feel is not the best way to do it.

推荐答案

处理在Web应用程序中找不到的正确方法是通过将404 HTTP状态代码返回给客户端,该状态代码在ASP.NET MVC术语中转换为返回您的控制器操作中的 HttpNotFoundResult :

The correct way to handle a not found in a web application is by returning a 404 HTTP status code to the client which in ASP.NET MVC terms translates into returning a HttpNotFoundResult from your controller action:

return new HttpNotFoundResult();

哦,哎呀,您没有注意到您仍在使用ASP.NET MVC2.您可以自己实现它,因为HttpNotFoundResult仅在ASP.NET MVC 3中引入:

Ahh, oops, didn't notice you were still on ASP.NET MVC 2. You could implement it yourself because HttpNotFoundResult was introduced only in 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;
    }
}

这篇关于找不到文件时处理FileContentResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆