Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 4 FileResult - In error

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

Works fine.

public FileResult GetReport(string id)
{
    byte[] fileBytes = _manager.GetReport(id);
    string fileName = id+ ".pdf";
    return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
}

When the manager fails to get the report I get back null or an empty byte[].

How can I communicate to the browser that there was a problem, when the result is set to a FileResult?

like image 981
Ian Vink Avatar asked Dec 02 '13 18:12

Ian Vink


2 Answers

I would change the return type of your method to ActionResult.

public ActionResult GetReport(string id)
{
    byte[] fileBytes = _manager.GetReport(id);
    if (fileBytes != null && fileBytes.Any()){
        string fileName = id+ ".pdf";
        return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
    }
    else {
        //do whatever you want here
        return RedirectToAction("GetReportError");
    }
}
like image 148
Adam Modlin Avatar answered Oct 19 '22 09:10

Adam Modlin


The FileResult class inherits from ActionResult. So, you can define your Action like this:

public ActionResult GetReport(string id)
{
    byte[] fileBytes = _manager.GetReport(id);
    string fileName = id + ".pdf";

    if(fileBytes == null || fileBytes.Length == 0)
       return View("Error");

    return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
}
like image 11
ataravati Avatar answered Oct 19 '22 07:10

ataravati