C# 捕获“超出最大请求长度”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/665453/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 12:28:39  来源:igfitidea点击:

Catching "Maximum request length exceeded"

c#asp.nethttpexception

提问by Marcus L

I'm writing an upload function, and have problems catching "System.Web.HttpException: Maximum request length exceeded" with files larger than the specified max size in httpRuntimein web.config (max size set to 5120). I'm using a simple <input>for the file.

我正在编写一个上传功能,并且在捕获“System.Web.HttpException:超出最大请求长度”的文件大于httpRuntimeweb.config 中指定的最大大小(最大大小设置为 5120)时遇到问题。我正在使用一个简单<input>的文件。

The problem is that the exception is thrown before the upload button's click-event, and the exception happens before my code is run. So how do I catch and handle the exception?

问题是在上传按钮的点击事件之前抛出异常,并且在我的代码运行之前发生异常。那么如何捕获和处理异常呢?

EDIT:The exception is thrown instantly, so I'm pretty sure it's not a timeout issue due to slow connections.

编辑:异常是立即抛出的,所以我很确定这不是由于连接缓慢导致的超时问题。

采纳答案by Damien McGivern

There is no easy way to catch such exception unfortunately. What I do is either override the OnError method at the page level or the Application_Error in global.asax, then check if it was a Max Request failure and, if so, transfer to an error page.

不幸的是,没有简单的方法可以捕获此类异常。我所做的是覆盖页面级别的 OnError 方法或 global.asax 中的 Application_Error,然后检查它是否是最大请求失败,如果是,则转移到错误页面。

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");
    }
}

It's a hack but the code below works for me

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

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;
}

回答by GateKiller

You can solve this by increasing the maximum request length in your web.config:

您可以通过增加 web.config 中的最大请求长度来解决此问题:

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

The example above is for a 100Mb limit.

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

回答by Jonathan Parker

As GateKiller said you need to change the maxRequestLength. You may also need to change the executionTimeout in case the upload speed is too slow. Note that you don't want either of these settings to be too big otherwise you'll be open to DOS attacks.

正如 GateKiller 所说,您需要更改 maxRequestLength。如果上传速度太慢,您可能还需要更改 executionTimeout。请注意,您不希望这些设置中的任何一个太大,否则您将受到 DOS 攻击。

The default for the executionTimeout is 360 seconds or 6 minutes.

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

You can change the maxRequestLength and executionTimeout with the httpRuntime Element.

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

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

EDIT:

编辑:

If you want to handle the exception regardless then as has been stated already you'll need to handle it in Global.asax. Here's a link to a code example.

如果你想处理异常,那么正如已经说明的那样,你需要在 Global.asax 中处理它。这是代码示例的链接。

回答by Vinod T. Patil

Hi solution mentioned by Damien McGivern, Works on IIS6 only,

嗨,Damien McGivern 提到的解决方案,仅适用于 IIS6,

It does not work on IIS7 and ASP.NET Development Server. I get page displaying "404 - File or directory not found."

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

Any ideas?

有任何想法吗?

EDIT:

编辑:

Got it... This solution still doesn't work on ASP.NET Development Server, but I got the reason why it was not working on IIS7 in my case.

明白了...这个解决方案仍然不能在 ASP.NET 开发服务器上运行,但是我知道为什么它在我的情况下不能在 IIS7 上运行。

The reason is IIS7 has a built-in request scanning which imposes an upload file cap which defaults to 30000000 bytes (which is slightly less that 30MB).

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

And I was trying to upload file of size 100 MB to test the solution mentioned by Damien McGivern (with maxRequestLength="10240" i.e. 10MB in web.config). Now, If I upload the file of size > 10MB and < 30 MB then the page is redirected to the specified error page. But if the file size is > 30MB then it show the ugly built-in error page displaying "404 - File or directory not found."

我试图上传大小为 100 MB 的文件来测试 Damien McGivern 提到的解决方案(在 web.config 中 maxRequestLength="10240" 即 10MB)。现在,如果我上传大小 > 10MB 和 < 30 MB 的文件,则页面将重定向到指定的错误页面。但是如果文件大小 > 30MB,那么它会显示丑陋的内置错误页面,显示“404 - 找不到文件或目录”。

So, to avoid this, you have to increase the max. allowed request content length for your website in IIS7. That can be done using following command,

因此,为了避免这种情况,您必须增加最大值。在 IIS7 中允许您的网站的请求内容长度。这可以使用以下命令完成,

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

I have set the max. content length to 200MB.

我已经设置了最大值。内容长度为 200MB。

After doing this setting, the page is succssfully redirected to my error page when I try to upload file of 100MB

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

Refer, http://weblogs.asp.net/jgalloway/archive/2008/01/08/large-file-uploads-in-asp-net.aspxfor more details.

有关更多详细信息,请参阅http://weblogs.asp.net/jgalloway/archive/2008/01/08/large-file-uploads-in-asp-net.aspx

回答by Marcus

回答by Andrew

If you are wanting a client side validation also so you get less of a need to throw exceptions you could try to implement client side file size validation.

如果您还需要客户端验证,因此您不需要抛出异常,您可以尝试实现客户端文件大小验证。

Note: This only works in browsers that support HTML5. http://www.html5rocks.com/en/tutorials/file/dndfiles/

注意:这只适用于支持 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>

回答by BaggieBoy

One way to do this is to set the maximum size in web.config as has already been stated above e.g.

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

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

then when you handle the upload event, check the size and if its over a specific amount, you can trap it e.g.

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

protected void btnUploadImage_OnClick(object sender, EventArgs e)
{
    if (fil.FileBytes.Length > 51200)
    {
         TextBoxMsg.Text = "file size must be less than 50KB";
    }
}

回答by BaggieBoy

In IIS 7 and beyond:

在 IIS 7 及更高版本中:

web.config file:

web.config 文件:

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

You can then check in code behind, like so:

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

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

Just make sure the [Size In Bytes] in the web.config is greater than the size of the file you wish to upload then you won't get the 404 error. You can then check the file size in code behind using the ContentLength which would be much better

只要确保 web.config 中的 [Size In Bytes] 大于您要上传的文件的大小,您就不会收到 404 错误。然后,您可以使用 ContentLength 在后面的代码中检查文件大小,这会好得多

回答by Nasurudeen

You can solve this by increasing the maximum request length and execution time out in your web.config:

您可以通过在 web.config 中增加最大请求长度和执行超时来解决此问题:

-Please Clarify the maximum execution time out grater then 1200

- 请说明最大执行超时大于 1200

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

回答by Serge Shultz

Here's an alternative way, that does not involve any "hacks", but requires ASP.NET 4.0 or later:

这是另一种方式,不涉及任何“黑客”,但需要 ASP.NET 4.0 或更高版本:

//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
    }
}