Catching Exception for "Maximum request length exceeded"

C

Chris Hayes

Greetings,

I have an ASP.NET page that accepts input from an HtmlInputFile object.

I have set the maximum size for HttpRequests to 2MB in the web.config file.

And now I am trying to CATCH the "Maximum request length exceeded"
HttpException when a user tries to send a file that is greater than 2MB so
that I may tell the user, gracefully, that their file is too big.

Now, my question is where in the world do I add a Handler for HttpException,
apparrently I'm not smart enough to know where this goes or to find any kind
of useful article on the subject (all the ones I have found, don't address
what I am trying to do, and worse yet don't give any real clear examples
just vague descriptions).

Thanks,

Chris
 
C

Chris Hayes

I figured it out...

I placed the code to handle it in the Application_Error method of the
global.asax file... I tend to overlook the global.asax nowadays...

Chris
 
J

Juan T. Llibre

Hi, Chris.

This should work...

In global.asax :
Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
Server.Transfer("Errors.aspx")
End Sub

The "errors.aspx" :
----------------------------
<html>
<script language="VB" runat="server">
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim errMessage As String = ""
Dim appException As System.Exception = Server.GetLastError()
If (TypeOf (appException) Is HttpException) Then
Dim checkException As HttpException = CType(appException, HttpException)
Select Case checkException.GetHttpCode
Case 403
errMessage &= "You are not allowed to view that page."
Case 404
errMessage &= "The page you have requested can't be found."
Case 408
errMessage &= "The request has timed out."
Case 500
errMessage &= "The server can't fulfill your request."
Case Else
errMessage &= "The server has experienced an error."
End Select
Else
errMessage &= "The following error occurred<BR>" & appException.ToString
End If
ErrorMessage.Text = errMessage & "<BR>Please contact the server's administrator."
Server.ClearError()
End Sub
</script>

<body>
<hr>
<asp:label id="ErrorMessage" font-size="12" font-bold="true" runat=server/>
<hr>
</body>
</html>
 
J

Juan T. Llibre

Chris,

Just add this case to the code I just sent you
in the "Well global.asax didn't work as well as hoped" thread :

Case 400
errMessage &= "Bad request. The file size is too large."

That will work fine for what you want to do.
 
C

Chris Hayes

Thanks Juan,

I tried what you provided and it worked up to a point, and then all kinds of
problems occurred again. It's not because of the code, it's because of how
ASP.NET handles Requests that exceed the maximum size.

I finally went with setting a custom error page for HTTP 400 (Request
exceeds maximum length). It doesn't allow me to do everything I want, but at
least it handles the error more gracefully.

Thanks again,

Chris

PS
I'm going to keep working on this (probably off and on). I want a more user
friendly handler for HTTP 400.
 
Joined
Feb 12, 2009
Messages
2
Reaction score
0
Catching Exception for "Maximum request length exceeded

Hi Guys,

This is the code below to redirect the same page if “Max Request Length Exception” occur. Just write this code on global.asax.

If the page content size is greater than maxRequestLength then this code redirect the page to the same page with query string action=exception. Just read this query string value and show the proper message the client browser.


protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpRuntimeSection runTime = (HttpRuntimeSection)WebConfigurationManager.GetSection("system.web/httpRuntime");
//Approx 100 Kb(for page content) size has been deducted because the maxRequestLength proprty is the page size, not only the file upload size
int maxRequestLength = (runTime.MaxRequestLength - 100) * 1024;

//This code is used to check the request length of the page and if the request length is greater than
//MaxRequestLength then retrun to the same page with extra query string value action=exception

HttpContext context = ((HttpApplication)sender).Context;
if (context.Request.ContentLength > maxRequestLength)
{
IServiceProvider provider = (IServiceProvider)context;
HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

// Check if body contains data
if (workerRequest.HasEntityBody())
{
// get the total body length
int requestLength = workerRequest.GetTotalEntityBodyLength();
// Get the initial bytes loaded
int initialBytes = 0;
if (workerRequest.GetPreloadedEntityBody() != null)
initialBytes = workerRequest.GetPreloadedEntityBody().Length;
if (!workerRequest.IsEntireEntityBodyIsPreloaded())
{
byte[] buffer = new byte[512000];
// Set the received bytes to initial bytes before start reading
int receivedBytes = initialBytes;
while (requestLength - receivedBytes >= initialBytes)
{
// Read another set of bytes
initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length);

// Update the received bytes
receivedBytes += initialBytes;
}
initialBytes = workerRequest.ReadEntityBody(buffer, requestLength - receivedBytes);
}
}
// Redirect the user to the same page with querystring action=exception.
context.Response.Redirect(this.Request.Url.LocalPath + "?action=exception");
}
}


Happy Coding
Rakesh Kumar
 
Last edited:
Joined
Oct 21, 2010
Messages
1
Reaction score
0
Already found it, thanks Google.

You read the bytes to prevent the browser thinking there is a TCP error because of the unread data.
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,037
Messages
2,570,371
Members
47,013
Latest member
JewellChes

Latest Threads

Top