Sanya530
Sanya530

Reputation: 1269

Setting maxRequestLength programmatically

There's a configuration value called maxRequestLength. In a config file it looks like this:

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

How can I set the value of maxRequestLength programmatically?

Upvotes: 4

Views: 7043

Answers (2)

Paul Fleming
Paul Fleming

Reputation: 24526

After a quick google, it appears you cannot do it programmatically. See here.

Two possible solutions:

  1. Use localized web.config to configure a particular directory.
  2. Use the <location> element in web.config to configure a particular path.

Upvotes: 3

Kamyar Nazeri
Kamyar Nazeri

Reputation: 26524

You can't!

maxRequestLength is handled by the HttpWorkerRequest prior the call to the actual HttpHandler, meaning that a generic handler or a page is executed after the request hit the server and has processed by the corresponding asp.net worker. you cannot have any control over the maxRequestLength in your page code or an HttpHandler!

If you want to read the request length in code you can do that either through a HttpModule or the global.asax file, this is how it is done inside the global.asax:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    IServiceProvider provider = (IServiceProvider)HttpContext.Current;
    HttpWorkerRequest workerRequest = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest));

    if (workerRequest.HasEntityBody())
    {
        long contentLength = long.Parse((workerRequest.GetKnownRequestHeader(HttpWorkerRequest.HeaderContentLength)));
    }
}

You could set the maxRequestLength in your web.config to its max value and call the worker's CloseConnection method in your code if the request length reaches the desired value!

Upvotes: 6

Related Questions