Handling FileContentResult when file is not found

爷,独闯天下 提交于 2019-11-29 18:28:41

问题


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");
}

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

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.


回答1:


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();

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;
    }
}



回答2:


In ASP.NET Core, use NotFound()

Your controller must inherit of Controller and the method must return ActionResult

Example:

public ActionResult GetFile(string path)
{
    if (!File.Exists(path))
    {
        return NotFound();
    }
    return new FileContentResult(File.ReadAllBytes(path), "application/octet-stream");
}


来源:https://stackoverflow.com/questions/6450495/handling-filecontentresult-when-file-is-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!