为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
弑天下 2019-09-20 15:11:46
我正在编写一个上传函数,并且httpRuntime在web.config中使用大于指定最大大小的文件时捕获“System.Web.HttpException:超出最大请求长度”时遇到问题(最大大小设置为5120)。我正在使用一个简单<input>的文件。问题是在上传按钮的click-event之前抛出了异常,并且异常发生在我的代码运行之前。那么如何捕获和处理异常呢?编辑:异常立即抛出,所以我很确定它不是由于连接速度慢导致的超时问题。
查看完整描述

3 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

不幸的是,没有简单的方法来捕获这样的例外。我所做的是覆盖页面级别的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");

    }

}

这是一个黑客,但下面的代码适合我


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;

}


查看完整回答
反对 回复 2019-09-20
?
翻翻过去那场雪

TA贡献2065条经验 获得超14个赞

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


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


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


<?xml version="1.0" encoding="utf-8"?>

<configuration>

    <system.web>

        <httpRuntime maxRequestLength="102400" executionTimeout="1200" />

    </system.web>

</configuration>

编辑:


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


查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 433 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信