ASP.NET MVC 4 FileResult - In error

后端 未结 4 1646
我寻月下人不归
我寻月下人不归 2021-02-19 20:35

I have a simple Action on a controller which returns a PDF.

Works fine.

public FileResult GetReport(string id)
{
    byte[] fileBytes = _manager.GetRepor         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-19 21:22

    If you want to "communicate to the browser" that there was an error, the standard "HTTP way" is to return status code 500, especially if your request is invoked using Ajax, so that you can gracefully handle the exception.

    I would suggest to simply throw an Exception when no report found for the provided id:

    public FileResult GetReport(string id)
    {
        // could internally throw the Exception inside 'GetReport' method
        byte[] fileBytes = _manager.GetReport(id);
    
        // or...
        if (fileBytes == null || !fileBytes.Any())
              throw new Exception(String.Format("No report found with id {0}", id));
    
        return File(fileBytes, MediaTypeNames.Application.Octet, fileName = id+ ".pdf");
    }
    

    Explicitly redirecting to an error page or returning a ViewResult is not the best approach in ASP.NET MVC as this is usually the role of the HandleError filter (which is applied by default) that can be easily configured to either redirect or render some View with the Exception details (while still maintaining HTTP status 500).

    This is all true assuming that a failure to fetch a report is indeed considered an exception. If it's not (for example, if we expect some report to not have an available file to dump), explicitly returning a Redirect/View result is totally acceptable.

提交回复
热议问题