最近一个项目需要用到HTTP文件上传功能,做过类似功能的朋友都知道,实现HTTP文件上传的功能并不难,使用ASP.NET就更加方便了,服务器端控件HtmlInputFile提供了强大的支持。一切进展得很顺利,功能很快就实现了,套用电视剧《美丽的田野》里那位周期性出现的家伙的一个词:一切看上去都十分“美观”。
但是当尝试上传较大的文件时,一切似乎变得“丑陋”起来—程序崩溃,而且出现“The page cannot be displayed”的错误页面。查阅相关资料后得知ASP.NET中默认的上传文件的最大值为4M,在web.config中可进行设置,但是即使设得再大,用户上传的文件都有可能超过限制。于是想到在Global.asax中的Application_Error事件处理过程中捕获“Maximum request length exceeded.”异常然后使页面Redirect至Custom Error Page。然而这个方法也行不通,虽然在Application_Error中可以捕获到“Maximum request length exceeded.”异常,但是页面无法Redirect至Custom Error Page,依旧是“The page cannot be displayed”。
事情一下变得棘手起来,很多技术文章也说这是HTTP协议为保证web服务器的稳定及安全所设的限制。就连微软官方的Support上也写着:“When the maxRequestLength attribute is set in the Machine.config file and then a request is posted (for example, a file upload) that exceeds the value of maxRequestLength, a custom error page cannot be displayed. Instead, Microsoft Internet Explorer will display a "Cannot find server or DNS" error message.”这看似一个受协议限制的无解问题。正当我打算就此作罢之际,无意间看到一片文章,根据其上所写的方案,这个问题居然解决了,真是山穷水复疑无路,柳暗花明又一村。
现将该方案按照我的思路整理出来,一来做一下总结,二来希望能对他人有所帮助。这固然有事后孔明之嫌,但毕竟还是好处多多。
前面说过,等Application_Error事件处理捕获到“Maximum request length exceeded.”异常为时已晚,页面已无法正常Redirect至Custom Error Page,因此应该设法使系统不抛出“Maximum request length exceeded.”异常。而要使系统不抛出该异常,就应在HttpHandler处理Request之前,使HttpHandler得到的HttpContext的内容小于maxRequestLength。看来,可以在Global.asax中的Application_BeginRequest事件处理过程中作一番文章。下面的代码就给出了解决方案:
1
private void Application_BeginRequest(Object source, EventArgs e)
2
{
3
HttpRequest request = HttpContext.Current.Request;
4
if (request.ContentLength > 4096000)//4096000 is maxRequestLength
5
{
6
HttpApplication app = source as HttpApplication;
7
HttpContext context = app.Context;
8
9
HttpWorkerRequest wr =
10
(HttpWorkerRequest)(context.GetType().GetProperty
11
("WorkerRequest", BindingFlags.Instance |
12
BindingFlags.NonPublic).GetValue(context, null));
13
byte[] buffer;
14
if (wr.HasEntityBody())
15
{
16
int contentlen = Convert.ToInt32(wr.GetKnownRequestHeader(
17
18
HttpWorkerRequest.HeaderContentLength));
19
buffer = wr.GetPreloadedEntityBody();
20
int received = buffer.Length;
21
int totalrecv = received;
22
if (!wr.IsEntireEntityBodyIsPreloaded())
23
{
24
buffer = new byte[65535];
25
while ( contentlen - totalrecv >= received )
26
{
27
received =
28
wr.ReadEntityBody(buffer,
29
buffer.Length);
30
totalrecv += received;
31
}
32
received =
33
wr.ReadEntityBody(buffer, contentlen - totalrecv);
34
}
35
}
36
context.Response.Redirect("../error.aspx");//Redirect to custom error page.
37
}