I'm writing an upload function, and have problems catching "System.Web.HttpException: Maximum request length exceeded" with files larger than the specified max size in httpRuntime
in web.config (max size set to 5120). I'm using a simple <input>
for the file.
The problem is that the exception is thrown before the upload button's click-event, and the exception happens before my code is run. So how do I catch and handle the exception?
EDIT: The exception is thrown instantly, so I'm pretty sure it's not a timeout issue due to slow connections.
As you probably know, the maximum request length is configured in TWO places.
maxRequestLength
- controlled at the ASP.NET app levelmaxAllowedContentLength
- under<system.webServer>
, controlled at the IIS levelThe first case is covered by other answers to this question.
To catch THE SECOND ONE you need to do this in global.asax:
There is no easy way to catch such exception unfortunately. What I do is either override the OnError method at the page level or the Application_Error in global.asax, then check if it was a Max Request failure and, if so, transfer to an error page.
It's a hack but the code below works for me
A solution that works with IIS7 and upwards: Display custom error page when file upload exceeds allowed size in ASP.NET MVC
One way to do this is to set the maximum size in web.config as has already been stated above e.g.
then when you handle the upload event, check the size and if its over a specific amount, you can trap it e.g.
In IIS 7 and beyond:
web.config file:
You can then check in code behind, like so:
Just make sure the [Size In Bytes] in the web.config is greater than the size of the file you wish to upload then you won't get the 404 error. You can then check the file size in code behind using the ContentLength which would be much better
After tag
add the following tag
you can add the Url to the error page...