29

When I upload an image I had this error:

maximum request length exceeded

How can I fix this problem?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Myworld
  • 1,861
  • 16
  • 45
  • 75
  • 1
    Possible duplicate of [Maximum request length exceeded](http://stackoverflow.com/questions/3853767/maximum-request-length-exceeded) – niico Nov 30 '16 at 04:48
  • Like niico said, for example, if you use more than one line in Web.config, you may get that error. – oguzhan Mar 06 '17 at 08:14

4 Answers4

60

Add the following to your web.config file:

<configuration>
   <system.web>
      <httpRuntime maxRequestLength ="2097151"/>
   </system.web>
</configuration>

This sets it to 2GB. Not certain what the max is.

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Ta01
  • 31,040
  • 13
  • 70
  • 99
  • 4
    Make sure that you're adding this to the main `Web.config` instead of the one inside the `Views` folder... – Serj Sagan Mar 04 '13 at 15:31
  • 3
    yes but how to catch this exception?Setting maxRequestLength to 2 GB I think is not the best choise .... – Nic Feb 18 '14 at 10:55
  • 1
    Just a quick note for anyone who may see this later... In the above example you are setting the max length to *2MB*, not 2GB. The request length is measured in bytes. So what you have is effectively 2,097Kb = ~2MB. Which isn't nearly as bad as 2GB :) – Josh Garwood Apr 02 '15 at 02:45
  • Actually according to the documentation, the field is specified in KB, so that *is* 2GB. – Eric Apr 21 '15 at 22:13
  • @dave, I couldn't see a way to do that, so I was hoping it would just get rejected. Just submitted a new edit suggestion to fix. – Eric Apr 21 '15 at 22:44
  • I'm getting this error when I try to upload a 4 mb exe disguised as a jpg even though my application allows 500 mb files. I want to restrict rogue files like exe renamed as jpg from being uploaded by hackers. so i'm actually checking the signature to determine the file type but the program isn't even going into my code and just crashing with this error right as soon as I select the file in my fileuploader control. Why??? – Partha Mandayam Aug 06 '23 at 09:54
21

You can increase the maximum length of requests in web.config, under <system.web>:

<httpRuntime maxRequestLength="100000" />

This example sets the maximum size to 100 MB.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Philippe Leybaert
  • 168,566
  • 31
  • 210
  • 223
9

That's not a terrific way to do it as you're basically opening up your server to DoS attacks allowing users to submit immense files. If you know that the user should only be uploading images of a certain size, you should be enforcing that rather than opening up the server to even larger submissions.

To do that you can use the example below.

As I was been moaned at for posting a link, I've added what I ultimately implemented using what I learned from the link I previously posted - and this has been tested and works on my own site...it assumes a default limit of 4 MB. You can either implement something like this, or alternatively employ some sort of third-party ActiveX control.

Note that in this case I redirect the user to the error page if their submission is too large, but there's nothing stopping you from customising this logic further if you so desired.

I hope it's useful.

public class Global : System.Web.HttpApplication {
    private static long maxRequestLength = 0;

    /// <summary>
    /// Returns the max size of a request, in kB
    /// </summary>
    /// <returns></returns>
    private long getMaxRequestLength() {

        long requestLength = 4096; // Assume default value
        HttpRuntimeSection runTime = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection; // check web.config
        if(runTime != null) {
            requestLength = runTime.MaxRequestLength;
        }
        else {
            // Not found...check machine.config
            Configuration cfg = ConfigurationManager.OpenMachineConfiguration();
            ConfigurationSection cs = cfg.SectionGroups["system.web"].Sections["httpRuntime"];
            if(cs != null) {
                requestLength = Convert.ToInt64(cs.ElementInformation.Properties["maxRequestLength"].Value);
            }
        }
        return requestLength;
    }

    protected void Application_Start(object sender, EventArgs e) {
        maxRequestLength = getMaxRequestLength();
    }

    protected void Application_End(object sender, EventArgs e) {

    }

    protected void Application_Error(object sender, EventArgs e) {
        Server.Transfer("~/ApplicationError.aspx");
    }

    public override void Init() {
        this.BeginRequest += new EventHandler(Global_BeginRequest);
        base.Init();
    }

    protected void Global_BeginRequest(object sender, EventArgs e) {

        long requestLength = HttpContext.Current.Request.ContentLength / 1024; // Returns the request length in bytes, then converted to kB

        if(requestLength > maxRequestLength) {
            IServiceProvider provider = (IServiceProvider)HttpContext.Current;
            HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

            // Check if body contains data
            if(workerRequest.HasEntityBody()) {

                // Get the total body length
                int bodyLength = 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(bodyLength - receivedBytes >= initialBytes) {

                        // Read another set of bytes
                        initialBytes = workerRequest.ReadEntityBody(buffer, buffer.Length);

                        // Update the received bytes
                        receivedBytes += initialBytes;
                    }
                    initialBytes = workerRequest.ReadEntityBody(buffer, bodyLength - receivedBytes);
                }
            }

            try {
                throw new HttpException("Request too large");
            }
            catch {
            }

            // Redirect the user
            Server.Transfer("~/ApplicationError.aspx", false);
        }
    }
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
burgen
  • 124
  • 1
  • 5
-1

To avoid maximum request length exceeded,dont upload large size image OR reduce image size between 100kb to 200kb .

Mati Ullah Zahir
  • 168
  • 1
  • 3
  • 13