Reputation: 3115
I'm relatively new to MVC but suppose I have a @Html.ActionLink(....
on my page that links to an Action that generates a file and returns it using:
return File(memoryStream, "application/vnd.ms-excel");
This all works well until there's some kind of issue - either something's gone wrong or there's no file to return.
Returning null
makes the webpage go to a blank page. So my question is... How can I gracefully handle this scenario? - ideally displaying some error to the user that something went wrong or there's no file/data available or if this isn't possible, then just ensuring the page doesn't go to a blank page, and just remains as it is.
I suppose I could redirect to the index action but this will refresh the page - are there any alternatives.
Upvotes: 1
Views: 2234
Reputation: 18783
I would do one of two things:
Return a 404 Not Found
response:
return HttpNotFound();
Render a "friendly" error page:
try
{
if (File.Exists(...))
{
// Download file
}
else
{
return View("FileNotFound");
}
}
catch (Exception ex)
{
return View("FileError", ex);
}
Upvotes: 1