我正在编写一个上传函数,但在捕获“System.Web.HttpException:超出最大请求长度”,文件大于指定的最大大小 httpRuntime在 web.config 中(最大大小设置为 5120)。我正在使用一个简单的 <input> 对于该文件。

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

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

有帮助吗?

解决方案

有没有简单的方法来捕捉这些异常不幸。我做的是任一覆盖在页级别的onError方法或在的Application_Error global.asax中,然后检查它是否是一个最高请求失败,并且如果是,转移到一个错误页面。

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

其他提示

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

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

您可以使用以下命令更改 maxRequestLength 和executionTimeout http运行时元素.

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

编辑:

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

可以通过在你的web.config增加最大请求长度解决这个问题:

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

上面的例子为100Mb的限制。

通过达明McGivern提到

您好溶液, 适用于只IIS6,

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

任何想法?

修改

明白了...这个解决方案仍然没有ASP.NET开发服务器上工作,但我为什么没有在IIS7的工作在我的情况的原因。

原因是IIS7具有规定的上传文件帽内置请求扫描缺省为30000000个字节(其略少是30MB)。

和我试图上载大小的文件100 MB,以测试由达明McGivern提到的溶液(具有的maxRequestLength web.config中=“10240”,即10MB)。现在,如果我上传大小> 10MB的文件和<30 MB,则页面重定向到指定的错误页面。但是,如果文件大小为> 30MB则显示显示丑内置的错误页面“404 - 文件或目录未找到”

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

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

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

这样设置后,页面succssfully重定向到我的错误页面,当我尝试上传100MB的文件

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

下面是另一种方式,不涉及任何“黑客”,但需要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
    }
}

这样做的一种方法是设置的最大尺寸在web.config中如上面已经指出例如

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

然后当你处理上载事件,检查尺寸,如果它超过一个特定的量,则可以捕获它 e.g。

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

在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比你要上传,那么你不会得到404错误的文件的大小。然后,您可以检查代码的文件大小背后使用的ContentLength这将是更好的。

您可能知道,最大请求长度配置在 地方。

  1. maxRequestLength - 在 ASP.NET 应用程序级别进行控制
  2. maxAllowedContentLength - 在下面 <system.webServer>, ,在 IIS 级别进行控制

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

去抓 第二个 你需要在 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();
    }
}

标签后

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

您可以将网址添加到错误页面...

可以通过增加最大请求长度和执行时间列于你的web.config解决这个问题:

- 请澄清最大执行时间进行研磨器1200然后

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

如何抓住它在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);
        }
    }

它可以通过检查:

        var httpException = ex as HttpException;
        if (httpException != null)
        {
            if (httpException.WebEventCode == System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge)
            {
                // Request too large

                return;

            }
        }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top