Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > ASP .Net > How to handle "Maximum request length exceeded" exception

Reply
Thread Tools

How to handle "Maximum request length exceeded" exception

 
 
=?Utf-8?B?Y21heQ==?=
Guest
Posts: n/a
 
      02-18-2005
I have changed my config files to set the limit for files being uploaded to
30 MB, but every now and then someone tries to upload a file larger than this.

All I want, is to be able to trap the error and tell the user what happened.

I can trap the error in the page_error (Page.Error) event, and I believe I
was also trapping it at the application_error level at one point.

My problem is, once I trap the error, I can't do anything to tell the user
what happened. If I try to display an error message in a asp.net label, or
response.write some text, or response.redirect them to another page, or just
set the errorPage property for the upload page to some URL, none of these
work.

When you upload a large file, the error is trapped correctly, and then the
browser shows the "Page cannot be displayed" message, no matter which of the
methods above I have tried.

Can anyone help me with this one?
 
Reply With Quote
 
 
 
 
Steve C. Orr [MVP, MCSD]
Guest
Posts: n/a
 
      02-18-2005
If the file is too large, an ugly error screen will be displayed to the user
and as far as I know there's nothing you can do about this without some kind
of thick client.

So to solve your problem, you might look into using a 3rd party activex
control such as this:
http://fileup.softartisans.com/fileup-231.aspx

--
I hope this helps,
Steve C. Orr, MCSD, MVP
http://SteveOrr.net


"cmay" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
>I have changed my config files to set the limit for files being uploaded to
> 30 MB, but every now and then someone tries to upload a file larger than
> this.
>
> All I want, is to be able to trap the error and tell the user what
> happened.
>
> I can trap the error in the page_error (Page.Error) event, and I believe I
> was also trapping it at the application_error level at one point.
>
> My problem is, once I trap the error, I can't do anything to tell the user
> what happened. If I try to display an error message in a asp.net label,
> or
> response.write some text, or response.redirect them to another page, or
> just
> set the errorPage property for the upload page to some URL, none of these
> work.
>
> When you upload a large file, the error is trapped correctly, and then the
> browser shows the "Page cannot be displayed" message, no matter which of
> the
> methods above I have tried.
>
> Can anyone help me with this one?



 
Reply With Quote
 
 
 
 
cmay
Guest
Posts: n/a
 
      02-21-2005
Steve,

Thanks for the reply.

I'm guessing that the reason I am not getting the normal ASP.NET error
page because I have error trapping at the page and application level.
So there is not an unhandled exception.

What I don't understand is why it seems like I can no longer relay
anything to the user once this error has occurred. I am wondering if
this is something to do with the nature of the exception, meaning that
the browser thinks it is still uploading the file (over the max amount)
while the server has already thrown the exception and stopped accepting
the upload?

I understand that this max input is put in place for security reasons,
but I can't believe that there is no way to display an error message to
the user, or direct them to an error page, in the event that they
exceed the maximum size for an upload.

If ASP.NET can give the user an ugly error page when this happens, I
should be able to give them a nice error page.

I understand that an ActiveX control would make this a lot easier, but
that is not an option for me for the obvious reasons.

Any idea where I can find more about this problem, or what I need to do
to give my users a nice error page?

Chris

 
Reply With Quote
 
rakeshkumarroy rakeshkumarroy is offline
Junior Member
Join Date: Feb 2009
Posts: 2
 
      02-13-2009
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.GetSec tion("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(Http WorkerRequest));

// 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.LocalPa th + "?action=exception");
}
}

Happy Coding
Rakesh Roy
 
Reply With Quote
 
Lazar Lazar is offline
Junior Member
Join Date: Mar 2009
Posts: 1
 
      03-18-2009
It works perfectly. The only thing I don't understand is why the whole request needs to be read for this to work? I've tried to make the redirection right after if (context.Request.ContentLength > maxRequestLength) but it didn't work. Anybody knows why?

thx
 
Reply With Quote
 
kevinAG kevinAG is offline
Junior Member
Join Date: Jan 2010
Posts: 1
 
      01-11-2010
Quote:
Originally Posted by Lazar
It works perfectly. The only thing I don't understand is why the whole request needs to be read for this to work? I've tried to make the redirection right after if (context.Request.ContentLength > maxRequestLength) but it didn't work. Anybody knows why?

thx
You must read all the data that is sent to the server, otherwise the browser will think there was a TCP connection error and fail. It will not listen to the response from the server until the server has listened to it. (At least that is what Chrome and Firefox 2.x appear to do. IE 6, however, appears to try the POST again before giving up and obeying the redirect response.) Check your IIS logs for details. For me, Firefox made one retry request and Chrome made four!

You can also put this code in the code behind of the specific page by overriding the ProcessRequest(HttpContext context) method.

Also note that this code does not handle the scenario where the request is made with "chunked encoding". Specifying the Content-Length Http header is not required in the Http 1.1 protocol. For a complete implementation, you can disassemble the code for the System.Web.HttpRequest.GetEntireRawContent() method in the System.Web.dll file using Reflector.
 
Reply With Quote
 
ComputerAngel ComputerAngel is offline
Junior Member
Join Date: Mar 2011
Posts: 1
 
      03-21-2011
Hi All,
This code works fine if you set

customErrors mode="Off" i-e Always display asp.net error information.
but if you set customErrors mode="On" or remoteonly, the below code redirects you to the
defaultRedirect url.

In production environment you can't set customErrors mode to "Off.

Any suggestions?

Quote:
Originally Posted by rakeshkumarroy View Post
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.GetSec tion("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(Http WorkerRequest));

// 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.LocalPa th + "?action=exception");
}
}

Happy Coding
Rakesh Roy
 
Reply With Quote
 
ksmetek ksmetek is offline
Junior Member
Join Date: Apr 2011
Posts: 1
 
      04-08-2011
Quote:
Originally Posted by Lazar View Post
It works perfectly. The only thing I don't understand is why the whole request needs to be read for this to work? I've tried to make the redirection right after if (context.Request.ContentLength > maxRequestLength) but it didn't work. Anybody knows why?

thx
It doesn't works perfect for me. I get an exception here: context.Response.Redirect(this.Request.Url.LocalPa th + "?action=exception");

Exception is something like: Exceeded request lenght. I tried put code in global asax and code behind. It's exactly same. I can catch HttpException but I can't redirect. "Cannot redirect after HTTP headers have been sent."

Hi I am new in ASP.net and I have same problem as author of this thread. When user attaches file using FileUpload control and then cllicks button add atachment, the post back is fired and when my request lenght is bigger than maxRequestLength in web.config I am getting httpException. I tried use your code but it's works until last line, where I get exception and I can't handle it

So, what should I do in order to fix problem. I tried clear context but when i do F5 refresh browser sending again request. After exit from public override void ProcessRequest(HttpContext context)I have blank page.Please tell me how can i do this code working ?
 
Reply With Quote
 
SilentSojourner SilentSojourner is offline
Junior Member
Join Date: Apr 2012
Posts: 1
 
      04-02-2012
Quote:
Originally Posted by ksmetek View Post
It doesn't works perfect for me. I get an exception here: context.Response.Redirect(this.Request.Url.LocalPa th + "?action=exception");

Exception is something like: Exceeded request lenght. I tried put code in global asax and code behind. It's exactly same. I can catch HttpException but I can't redirect. "Cannot redirect after HTTP headers have been sent."

Hi I am new in ASP.net and I have same problem as author of this thread. When user attaches file using FileUpload control and then cllicks button add atachment, the post back is fired and when my request lenght is bigger than maxRequestLength in web.config I am getting httpException. I tried use your code but it's works until last line, where I get exception and I can't handle it

So, what should I do in order to fix problem. I tried clear context but when i do F5 refresh browser sending again request. After exit from public override void ProcessRequest(HttpContext context)I have blank page.Please tell me how can i do this code working ?
A simple fix is to put this code in Applicatino_Error in global.asax.cs:

Exception ex = Server.GetLastError();
if (ex.InnerException != null && ex.InnerException.Message.Contains("Maximum request length exceeded"))
{
Server.ClearError();
Response.Redirect(
"mypage.aspx");
}

A late reply indeed. But hope it helps other visitors.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Bugs: Content-Length not updated by reused urllib.request.Request/ has_header() case-sensitive Johannes Kleese Python 4 11-27-2012 11:24 PM
Re: Bugs: Content-Length not updated by reusedurllib.request.Request / has_header() case-sensitive Cameron Simpson Python 0 11-12-2012 10:59 PM
Catching Exception for "Maximum request length exceeded" Chris Hayes ASP .Net 8 10-21-2010 02:02 PM
Handle C++ exception and structured exception together George2 C++ 15 01-29-2008 07:34 AM
Possible to handle web requests without an ASPX page? i.e. have DLL handle request. jdlwright@shaw.ca ASP .Net 2 05-31-2005 05:42 PM



Advertisments