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

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

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

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


弑天下
浏览 434回答 3
3回答

撒科打诨

不幸的是,没有简单的方法来捕获这样的例外。我所做的是覆盖页面级别的OnError方法或global.asax中的Application_Error,然后检查它是否是最大请求失败,如果是,则转移到错误页面。protected override void OnError(EventArgs e) .....private void Application_Error(object sender, EventArgs e){&nbsp; &nbsp; if (GlobalHelper.IsMaxRequestExceededException(this.Server.GetLastError()))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; this.Server.ClearError();&nbsp; &nbsp; &nbsp; &nbsp; this.Server.Transfer("~/error/UploadTooLarge.aspx");&nbsp; &nbsp; }}这是一个黑客,但下面的代码适合我const int TimedOutExceptionCode = -2147467259;public static bool IsMaxRequestExceededException(Exception e){&nbsp; &nbsp; // unhandled errors = caught at global.ascx level&nbsp; &nbsp; // http exception = caught at page level&nbsp; &nbsp; Exception main;&nbsp; &nbsp; var unhandled = e as HttpUnhandledException;&nbsp; &nbsp; if (unhandled != null && unhandled.ErrorCode == TimedOutExceptionCode)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; main = unhandled.InnerException;&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; main = e;&nbsp; &nbsp; }&nbsp; &nbsp; var http = main as HttpException;&nbsp; &nbsp; if (http != null && http.ErrorCode == TimedOutExceptionCode)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // hack: no real method of identifying if the error is max request exceeded as&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; // it is treated as a timeout exception&nbsp; &nbsp; &nbsp; &nbsp; if (http.StackTrace.Contains("GetEntireRawContent"))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // MAX REQUEST HAS BEEN EXCEEDED&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return false;}

翻翻过去那场雪

正如GateKiller所说,你需要改变maxRequestLength。如果上传速度太慢,您可能还需要更改executionTimeout。请注意,您不希望这些设置中的任何一个太大,否则您将对DOS攻击开放。executionTimeout的默认值为360秒或6分钟。您可以使用httpRuntime元素更改maxRequestLength和executionTimeout 。<?xml version="1.0" encoding="utf-8"?><configuration>&nbsp; &nbsp; <system.web>&nbsp; &nbsp; &nbsp; &nbsp; <httpRuntime maxRequestLength="102400" executionTimeout="1200" />&nbsp; &nbsp; </system.web></configuration>编辑:如果你想要处理异常,那么就像已经说明的那样,你需要在Global.asax中处理它。这是代码示例的链接。
打开App,查看更多内容
随时随地看视频慕课网APP