代码之家  ›  专栏  ›  技术社区  ›  Marcus L

捕获“超过最大请求长度”

  •  107
  • Marcus L  · 技术社区  · 16 年前

    httpRuntime 在web.config中(最大大小设置为5120)。我用的是一个简单的 <input> 为了这个文件。

    编辑: 异常会立即抛出,因此我非常确定这不是由于连接速度慢而导致的超时问题。

    13 回复  |  直到 10 年前
        1
  •  97
  •   Pona user453222    9 年前

    不幸的是,没有简单的方法可以捕获这样的异常。我要做的是在页面级别重写OnError方法,或者在global.asax中重写Application_错误,然后检查它是否是Max请求失败,如果是,则转移到错误页面。

    protected override void OnError(EventArgs e) .....
    
    
    private void Application_Error(object sender, EventArgs e)
    {
        if (GlobalHelper.IsMaxRequestExceededException(this.Server.GetLastError()))
        {
            this.Server.ClearError();
            this.Server.Transfer("~/error/UploadTooLarge.aspx");
        }
    }
    

    这是一个黑客,但下面的代码对我来说很有用

    const int TimedOutExceptionCode = -2147467259;
    public static bool IsMaxRequestExceededException(Exception e)
    {
        // unhandled errors = caught at global.ascx level
        // http exception = caught at page level
    
        Exception main;
        var unhandled = e as HttpUnhandledException;
    
        if (unhandled != null && unhandled.ErrorCode == TimedOutExceptionCode)
        {
            main = unhandled.InnerException;
        }
        else
        {
            main = e;
        }
    
    
        var http = main as HttpException;
    
        if (http != null && http.ErrorCode == TimedOutExceptionCode)
        {
            // hack: no real method of identifying if the error is max request exceeded as 
            // it is treated as a timeout exception
            if (http.StackTrace.Contains("GetEntireRawContent"))
            {
                // MAX REQUEST HAS BEEN EXCEEDED
                return true;
            }
        }
    
        return false;
    }
    
        2
  •  58
  •   schellack    13 年前

    executionTimeout的默认值为360秒或6分钟。

    您可以使用更改maxRequestLength和executionTimeout httpRuntime Element .

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <system.web>
            <httpRuntime maxRequestLength="102400" executionTimeout="1200" />
        </system.web>
    </configuration>
    

    如果您想处理异常,那么正如前面所述,您需要在Global.asax中处理它。这里有一个链接到 code example .

        3
  •  20
  •   GateKiller    16 年前

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <system.web>
            <httpRuntime maxRequestLength="102400" />
        </system.web>
    </configuration>
    

    上面的示例是针对100Mb限制的。

        4
  •  10
  •   Andrew    13 年前

    注意:这只适用于支持HTML5的浏览器。 http://www.html5rocks.com/en/tutorials/file/dndfiles/

    <form id="FormID" action="post" name="FormID">
        <input id="target" name="target" class="target" type="file" />
    </form>
    
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
    
    <script type="text/javascript" language="javascript">
    
        $('.target').change(function () {
    
            if (typeof FileReader !== "undefined") {
                var size = document.getElementById('target').files[0].size;
                // check file size
    
                if (size > 100000) {
    
                    $(this).val("");
    
                }
            }
    
        });
    
    </script>
    

        5
  •  9
  •   Vinod T. Patil    14 年前

    仅适用于IIS6,

    它在IIS7和ASP.NET开发服务器上不起作用。我得到的页面显示“404-未找到文件或目录”

    原因是IIS7有一个内置的请求扫描,该扫描强制使用上传文件上限,默认值为30000000字节(略小于30MB)。

    因此,为了避免这种情况,您必须在IIS7中增加网站允许的最大请求内容长度。

    appcmd set config "SiteName" -section:requestFiltering -requestLimits.maxAllowedContentLength:209715200 -commitpath:apphost
    

    我已将最大内容长度设置为200MB。

    完成此设置后,当我尝试上载100MB的文件时,页面将成功重定向到我的错误页面

    参考 http://weblogs.asp.net/jgalloway/archive/2008/01/08/large-file-uploads-in-asp-net.aspx 更多细节。

        6
  •  8
  •   Serge Shultz    10 年前

    //Global.asax
    private void Application_Error(object sender, EventArgs e)
    {
        var ex = Server.GetLastError();
        var httpException = ex as HttpException ?? ex.InnerException as HttpException;
        if(httpException == null) return;
    
        if(httpException.WebEventCode == WebEventCodes.RuntimeErrorPostTooLarge)
        {
            //handle the error
            Response.Write("Sorry, file is too big"); //show this message for instance
        }
    }
    
        7
  •  4
  •   BaggieBoy    12 年前

    一种方法是在web.config中设置最大大小,如上所述。

    <system.web>         
        <httpRuntime maxRequestLength="102400" />     
    </system.web>
    

    然后,在处理上载事件时,检查大小,如果超过特定数量,则可以捕获它 例如

    protected void btnUploadImage_OnClick(object sender, EventArgs e)
    {
        if (fil.FileBytes.Length > 51200)
        {
             TextBoxMsg.Text = "file size must be less than 50KB";
        }
    }
    
        8
  •  3
  •   Community CDub    8 年前
        9
  •  3
  •   Walery Strauch Lia    11 年前

    在IIS 7及更高版本中:

    web.config文件:

    <system.webServer>
      <security >
        <requestFiltering>
          <requestLimits maxAllowedContentLength="[Size In Bytes]" />
        </requestFiltering>
      </security>
    </system.webServer>
    

    然后可以签入代码隐藏,如下所示:

    If FileUpload1.PostedFile.ContentLength > 2097152 Then ' (2097152 = 2 Mb)
      ' Exceeded the 2 Mb limit
      ' Do something
    End If
    

    只要确保web.config中的[Size In Bytes]大于您希望上载的文件的大小,就不会出现404错误。然后,您可以使用ContentLength检查代码隐藏中的文件大小,这会更好

        10
  •  2
  •   jazzcat    8 年前

    地方。

    1. maxRequestLength
    2. maxAllowedContentLength <system.webServer>

    对这个问题的其他答案涵盖了第一种情况。

    捉住 第二个 您需要在global.asax中执行此操作:

    protected void Application_EndRequest(object sender, EventArgs e)
    {
        //check for the "file is too big" exception if thrown at the IIS level
        if (Response.StatusCode == 404 && Response.SubStatusCode == 13)
        {
            Response.Write("Too big a file"); //just an example
            Response.End();
        }
    }
    
        11
  •  1
  •   Diego    9 年前

    <security>
         <requestFiltering>
             <requestLimits maxAllowedContentLength="4500000" />
         </requestFiltering>
    </security>
    

    添加以下标记

     <httpErrors errorMode="Custom" existingResponse="Replace">
      <remove statusCode="404" subStatusCode="13" />
      <error statusCode="404" subStatusCode="13" prefixLanguageFilePath="" path="http://localhost/ErrorPage.aspx" responseMode="Redirect" />
    </httpErrors>
    

        12
  •  1
  •   Martin van Bergeijk    4 年前

    我正在使用FileUpload控件和客户端脚本来检查文件大小。
    HTML(注意OnClientClick-在OnClick之前执行):

    <asp:FileUpload ID="FileUploader" runat="server" />
    <br />
    <asp:Button ID="btnUpload" Text="Upload" runat="server" OnClientClick="return checkFileSize()" OnClick="UploadFile" />
    <br />
    <asp:Label ID="lblMessage" runat="server" CssClass="lblMessage"></asp:Label>
    

    然后是脚本(如果大小太大,请注意“return false”:这是为了取消OnClick):

    function checkFileSize() 
    {
        var input = document.getElementById("FileUploader");
        var lbl = document.getElementById("lblMessage");
        if (input.files[0].size < 4194304)
        {
            lbl.className = "lblMessage";
            lbl.innerText = "File was uploaded";
        }
        else
        {
            lbl.className = "lblError";
            lbl.innerText = "Your file cannot be uploaded because it is too big (4 MB max.)";
            return false;
        }
    }
    
        13
  •  0
  •   Nasurudeen    11 年前

    -请澄清最长执行超时时间,然后是1200

    <?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <httpRuntime maxRequestLength="102400" executionTimeout="1200" /> </system.web> </configuration>
    
        14
  •  0
  •   Khoa Tran    9 年前

    在EndRequest事件中捕获它怎么样?

    protected 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);
            }
        }
    
        15
  •  0
  •   Raghav    6 年前

    可通过以下方式进行检查:

            var httpException = ex as HttpException;
            if (httpException != null)
            {
                if (httpException.WebEventCode == System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge)
                {
                    // Request too large
    
                    return;
    
                }
            }
    
        16
  •  0
  •   pmcs    3 年前

    继Martin van Bergeijk的回答之后,我添加了一个额外的if块,以检查他们是否在提交之前选择了一个文件。

    if(input.files[0] == null)
    {lbl.innertext = "You must select a file before selecting Submit"}
    return false;