首先,在Global.asax.cs中实现Application_BeginRequest方法,实例HttpWorkerRequest wr = (HttpWorkerRequest)provider.GetService(typeof(HttpWorkerRequest))来获取web.config中的maxLength长度,同时开辟一个内存wr(大小为maxLength);然后用GetPreloadedEntityBody()方法获取上传的文件的内容。对文件内容长度进行判断,如果文件大于2MB(request.ContentLength > 2097152),则用ReadEntityBody()方法读取文件的n个字符,读入wr中,当读入的数据〉wr的大小时,Maximum request length exceeded异常触发。
于是在Global.asax.cs中实现Application_Error方法,判断如果获得的异常type为Maximum request length exceeded,则定位到错误页面(Error.asp)页面内容“上传的文件太大”。
void Application_BeginRequest(object source, EventArgs e)
{
IServiceProvider provider = (IServiceProvider) HttpContext.Current;
HttpWorkerRequest wr = (HttpWorkerRequest) provider.GetService(typeof(HttpWorkerRequest));
byte[] bs = wr.GetPreloadedEntityBody();
HttpRequest request = HttpContext.Current.Request;
if (request.ContentLength > 2097152)
{
if (!wr.IsEntireEntityBodyIsPreloaded())
{
int n = 65535;
byte[] bs2 = new byte[n];
while (wr.ReadEntityBody(bs2, n) > 0)
{
}
}
//Response.Redirect("~/About.aspx");
}
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception exc = Server.GetLastError();
// Handle HTTP errors
if (exc.GetType() == typeof(HttpUnhandledException))
{
if (exc.InnerException.Message.Contains("Maximum request length exceeded."))
Response.Redirect("~/Error.aspx");
//exc.InnerException.
}
}