I have a directory "Downloads" where I have static files that our clients can download. I am using the the following ActionLink to call the file:
@Html.ActionLink("Download Example", "Download", new { area = "", controller = "Common", fileName = "SomeFile.xlsx" })
that calls the "Common" controller and returns the file using the code below:
public FileStreamResult Download(string fileName)
{
var filePath = Server.MapPath("~/Download/" + fileName);
var ext = Path.GetExtension(fileName);
switch (ext)
{
case ".xlsx":
return new FileStreamResult(new FileStream(filePath, FileMode.Open),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
case ".xls":
return
new FileStreamResult(
new FileStream(Server.MapPath("~/Download/" + fileName), FileMode.Open),
"application/vnd.ms-excel");
case ".pdf":
return
new FileStreamResult(
new FileStream(Server.MapPath("~/Download/" + fileName), FileMode.Open),
"application/pdf");
}
return null;
}
}
My question is that since I am not returning a view, how can I return a message to the View to show if the file is not there (404)?
I have figured out this much:
if (!System.IO.File.Exists(filePath))
{
}
but I have no idea on what to return to avoid a 404 redirect. I want to return a message "File not found" or something similar within the page rather than the page redirecting to the 404 error page.
throw new HttpException(404, "File not found")
otherwise you need to change your return type. And anything other than a native HTTP response code is bad practice. besides, you can use filters to handle the "not found" message however you'd like (to the client). – Reg