Windows – Catching “request entity is too large” error

asp.neterror handlingiisiis-8windows

I am running a web server IIS 8.0 and using ASP.NET and C#.

I have an upload box where the user can upload a file to the server and after a limit of about 50MB, a message appears on a white page:

The page was not displayed because the request entity is too large.

I'd like to display a more user-friendly page with a notification in red that says "Error trying to upload your file, please contact us for help."

In my codebehind file when handling the upload button click event, I added:

try
{
    //try to save the file to server
}
catch(Exception ex)
{
    //otherwise, set the asp:Label tag text to display error
}

However, the code in the catch statement is not being run. My guess is that the error may lie with IIS and can't be caught with that statement of code. Is there any way to intercept that error and display a friendlier error page instead?

Thank you for your help.

Best Answer

If the uploaded file is larger than allowed by IIS, it will never reach the ASP.NET runtime and your exception handling is useless.

You should set uploadReadAheadSize to much higher than you want to allow, ideally only for the specific URL. And then check for the upload size in your code and display your own message.

If the user uploads a huge file larger than uploadReadAheadSize he/she still gets the IIS message but this case it much less likely if you use a big number.