Error handling when downloading file from ASP.NET Web Handler (.ashx)

First of all on this answer of mine the user ask how to make the download with javascript. But if you have the link you do not necessary need to add it to javascript, you can add it also using a regular download link.

Now many web sites use a page with some text that says “and now your download will start in few seconds. If not start please click here bla bla bla“. One of the reasons is similar to yours, the user must know that something will start the download in few seconds and if not, then the user understand that there is a problem with out other extra message.

In general when you going to send a file for download, you are not in the page any more, you can not send message in the middle of the download, – or when the file ends with pdf, then is probably not going to show anything on a web page. So from my point of view if you do have issues and throw exceptions, you need to design some steps on how you inform the user that something was going wrong – like the middle page that inform the user that “now you going to receive a file – if the file not start the download in few seconds please do that”

However, when there is an exception thrown in the handler they are
redirected to the URL of the handler and shown a blank page.

To avoid that black page, on error you can return that code and the user is stay on page as it is, but still did not get any error message.

Response.TrySkipIisCustomErrors = true;
Response.Status = "204 No Content";
Response.StatusCode = 204;
Response.End();

Alternative on exception you can try to redirect him to an error page using the

Response.Redirect("errorpage.aspx");

and maybe you can send and some error ids there.

You can also try to just show a simple message as

context.Response.ContentType = "text/html";
context.Response.Write("Error downloading file - Please contact with us");

Leave a Comment