Handling FileContentResult when file is not found

前端 未结 2 1977
别跟我提以往
别跟我提以往 2020-12-31 10:51

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 somet

相关标签:
2条回答
  • 2020-12-31 11:04

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-31 11:15

    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");
    }
    
    0 讨论(0)
提交回复
热议问题