How to handle "Maximum request length exceeded" exception

Discussion in 'ASP .Net' started by Guest, Feb 18, 2005.

  1. Guest

    Guest Guest

    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 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

    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?
    Guest, Feb 18, 2005
    1. Advertisements

  2. 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:
    Steve C. Orr [MVP, MCSD], Feb 18, 2005
    1. Advertisements

  3. Guest

    cmay Guest


    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?

    cmay, Feb 21, 2005
  4. Guest


    Feb 12, 2009
    Likes Received:
    Max Request Lenght Exception Handling

    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 Roy
    rakeshkumarroy, Feb 13, 2009
  5. Guest


    Mar 18, 2009
    Likes Received:
    But why?

    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?

    Lazar, Mar 18, 2009
  6. Guest


    Jan 10, 2010
    Likes Received:
    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.
    kevinAG, Jan 11, 2010
  7. Guest


    Mar 21, 2011
    Likes Received:
    Hi All,
    This code works fine if you set

    customErrors mode="Off" i-e Always display 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?

    ComputerAngel, Mar 21, 2011
  8. Guest


    Apr 8, 2011
    Likes Received:
    It doesn't works perfect for me. I get an exception here: context.Response.Redirect(this.Request.Url.LocalPath + "?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 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 ?
    ksmetek, Apr 8, 2011
  9. Guest


    Apr 2, 2012
    Likes Received:
    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"))

    A late reply indeed. But hope it helps other visitors.
    SilentSojourner, Apr 2, 2012
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.