A better way of handling maxRequestLength exceptions

ASP.NET 2 includes the FileUpload control to make it easier to create pages that allow users to upload files. The default maximum file size is 4096 KB to minimize the potential for denial of service attacks. You can change the maximum file size by editing your configuration files (see for example http://msdn2.microsoft.com/en-US/library/system.web.configuration.httpruntimesection.maxrequestlength(VS.80).aspx and http://support.softartisans.com/kbview_825.aspx).

The problem is that when users attempt to upload a file that is too large, it is difficult to capture and handle the exception that is created. The usual try..catch doesn’t handle the exception because the exception occurs before then. The exception is “System.Web.HttpException: Maximum request length exceeded”. You could of course increase the maximum file size but that defeats the purpose of the limit in the first place.

Here is one solution for handling the exception that is at least nicer than the standard ASP.NET exception message:

1. Create a global.asax file. If you’re using Visual Studio 2005 it will set up a number of common subroutines for you. You need to use Sub Application_Error. Your code should look something like this:

<script runat=”server”>
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Dim currentException As Exception
currentException = Server.GetLastError.GetBaseException()
Response.Redirect(“/error.aspx?Err=” & Server.UrlEncode(currentException.Message))
End Sub
</script>

The application_Error sub fires as a last resort, in other words, when you haven’t explicitly handled the exception anywhere else in your code.

2. You can now create an error.aspx that displays the exception message (from the querystring). For this exception the message is “Maximum request length exceeded”. You could also test for the message and give users more information on the error.

Please let me know if you have any comments, suggestions, or improvements.

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)