问题描述
我正在编写一个上传函数,并且在捕获System.Web.HttpException:最大请求长度超出"时遇到问题,文件大于 web.config 中 httpRuntime
中指定的最大大小(最大大小设置为 5120).我正在为文件使用一个简单的 .
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 httpRuntime
in web.config (max size set to 5120). I'm using a simple <input>
for the file.
问题是在上传按钮的点击事件之前抛出异常,并且在我的代码运行之前发生异常.那么我该如何捕捉和处理异常呢?
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?
异常立即抛出,所以我很确定这不是由于连接缓慢导致的超时问题.
The exception is thrown instantly, so I'm pretty sure it's not a timeout issue due to slow connections.
推荐答案
不幸的是,没有简单的方法可以捕获此类异常.我所做的是在页面级别覆盖 OnError 方法或 global.asax 中的 Application_Error,然后检查它是否是最大请求失败,如果是,则转移到错误页面.
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.
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;
}
这篇关于捕获“超出最大请求长度"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!