以编程方式设置maxRequestLength

4

有一个配置值叫做maxRequestLength。在配置文件中看起来像这样:

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

我该如何以编程方式设置maxRequestLength的值?
2个回答

6
你无法控制maxRequestLength! 在调用实际的 HttpHandler 之前,maxRequestLengthHttpWorkerRequest处理,这意味着请求被服务器接收并且已由相应的asp.net worker进行处理后,才会执行通用处理程序或页面。你无法在页面代码或者一个HttpHandler中对maxRequestLength进行任何控制!
如果你想在代码中读取请求长度,你可以通过HttpModuleglobal.asax 文件来实现,在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)));
    }
}

如果请求长度达到所需值,您可以在代码中调用工作线程的CloseConnection方法,并将web.config中的maxRequestLength设置为最大值!


以下似乎是读取设置的更简单的解决方案。https://dev59.com/r2445IYBdhLWcg3wZJUn - Mike Schall
@MikeSchall OP指出如何更改maxRequestLength,这是不可能的。上面的代码片段是如何读取任何请求的content-length,而不是最大长度。 - Kamyar Nazeri

3
经过快速搜索,似乎无法通过编程实现。请参见此处
两种可能的解决方案:
  1. 使用本地化的web.config来配置特定目录。
  2. 使用web.config中的<location>元素来配置特定路径。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接