在IIS7中,我在哪里捕获并处理maxAllowedContentLength?

sun*_*wer 13 iis-7 web-config httpapplication http-status-code-404

我有一个aspx页面,我允许用户上传文件,我想将最大文件上传大小限制为10MB.IIS7,.NET 3.5.我在web.config文件中配置了以下内容:

<location path="foo.aspx">
    <system.web>
        <!-- maxRequestLength: kbytes, executionTimeout:seconds -->
        <httpRuntime maxRequestLength="10240" executionTimeout="120" />
        <authorization>
            <allow roles="customRole"/>
            <!-- Deny everyone else -->
            <deny users="*"/>
        </authorization>
    </system.web>
    <system.webServer>
        <security>
            <requestFiltering>
                <!-- maxAllowedContentLength: bytes -->
                <requestLimits maxAllowedContentLength="10240000"/>
            </requestFiltering>
        </security>
        <handlers accessPolicy="Read, Script">
            <add name="foo" path="foo.aspx" verb="POST"
               type="System.Web.UI.PageHandlerFactory"
               preCondition="integratedMode" />
        </handlers>       
    </system.webServer>
</location>
Run Code Online (Sandbox Code Playgroud)

我有一个实现的自定义错误处理模块IHttpModule.我发现当maxRequestLength超过时,HttpApplication.Error确实会被提升.但是当我玩游戏时maxAllowedContentLength,HttpApplication.Error事件没有被引发,用户被重定向到404.13页面.我已经附加了Visual Studio,第一次机会异常打开,没有任何东西被抛出.

我的第一个想法是检查早期事件中的标题内容长度 - 是否有建议/最佳实践我在哪里这样做?PostLogRequest?EndRequest?

sun*_*wer 14

在查看IIS 7.0ASP.NET应用程序生命周期概述并进行自己的实验之后,我假设在引发任何事件之前,IIS内部完成请求验证.

看起来只有LogRequest,PostLogRequest,EndRequest,PreSendRequestContent和PreSendRequestHeaders在内部验证后引发此错误.

我决定HttpApplication.EndRequest在我的自定义错误处理程序中为事件附加一个事件处理程序,并检查POST上的404.13状态代码并处理,因为我需要处理它,在我的情况下是重定向到将检查的调用页面Server.GetLastError()并向最终用户显示友好错误.

private void application_EndRequest(object sender, EventArgs e)
{
    HttpRequest request = HttpContext.Current.Request;
    HttpResponse response = HttpContext.Current.Response;

    if ((request.HttpMethod == "POST") &&
        (response.StatusCode == 404 && response.SubStatusCode == 13))
    {
        // Clear the response header but do not clear errors and
        // transfer back to requesting page to handle error
        response.ClearHeaders();
        HttpContext.Current.Server.Transfer(
            request.AppRelativeCurrentExecutionFilePath);
    }
}
Run Code Online (Sandbox Code Playgroud)

我欢迎对这种方法和替代方案的反馈.