2012-12-25 96 views
4

有一個名爲maxRequestLength的配置值。在一個配置文件,它看起來像這樣:以編程方式設置maxRequestLength

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

我怎樣才能設置maxRequestLength編程的價值?

回答

6

你不能!

maxRequestLengthHttpWorkerRequest現有呼叫處理,以實際HttpHandler,這意味着請求命中已經由相應的asp.net工人處理的服務器之後的通用處理程序或頁被執行。您無法控制頁面代碼中的maxRequestLength或HttpHandler!

如果你想讀在代碼中請求長度,你可以做,要麼通過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))); 
    } 
} 

您可以設置maxRequestLengthweb.config設置爲最大值,如果請求長度達到所需值,則在代碼中調用工作人員的CloseConnection方法!

+0

以下看起來像是一個更簡單的解決方案來閱讀設置。 http://stackoverflow.com/questions/4887016/how-to-access-httpruntime-section-of-web-config-from-codebehind –

+0

@MikeSchall OP指出如何更改maxRequestLength,這是不可能的,代碼片段以上是如何讀取任何請求的內容長度,而不是最大長度 –

3

經過快速的谷歌,看起來你不能以編程方式做到這一點。 See here

兩個可能的解決方案:

  1. 使用本地化的web.config配置特定的目錄。
  2. 使用web.config中的<location>元素來配置特定路徑。