前面有篇随笔,记录了自己对网站异常的捕获和处理方式。但几天用下来,突然发现一个问题,就是在IE下有的时候不能显示正确的报错页面,而是显示那种一般在网络终端的时候才会出现的IE报错页面:
而同样的报错页面,在FireFox下却显示得很好,和设计预期一致:
下面贴出系统里在捕获了异常后执行的处理代码:
1public static void ShowError(string errMsg)
2{
3 string localErr = "执行过程中出错,错误信息为:";
4 if (errMsg == null)
5 localErr += "无";
6 else
7 localErr += errMsg;
8
9 localErr = HttpContext.Current.Server.UrlEncode(localErr);
10 HttpContext.Current.Response.Redirect(string.Format("~/ShowError.aspx?ErrString='{0}'", localErr), true);
11 HttpContext.Current.Response.End();
12}
2{
3 string localErr = "执行过程中出错,错误信息为:";
4 if (errMsg == null)
5 localErr += "无";
6 else
7 localErr += errMsg;
8
9 localErr = HttpContext.Current.Server.UrlEncode(localErr);
10 HttpContext.Current.Response.Redirect(string.Format("~/ShowError.aspx?ErrString='{0}'", localErr), true);
11 HttpContext.Current.Response.End();
12}
看到上面的代码段,我想一些Web开发经验比较丰富的朋友已经看出问题来了。是的,在这里,出错信息是被加到Url里传递给出错页面的,但IE的地址栏所能支持的字符串长度是很有限的!我自己试了一下,在IE7的地址栏里只能输入不超过2048个英文字符,看微软的介绍,应该是2083个,总之相差不大。其实,对于Response.Redirect($url)方法,以前知道使用它相当于从客户端重新请求$url,但以为仅仅是“相当于”,其实还是服务器上面的直接跳转。但通过把过长报错字符串传递给$url所看到的IE中的反应,这里其实就是从客户端重新发出了请求。知道了问题,解决起来就很容易了,把上面的代码修改如下即可:
1public static void ShowError(string errMsg)
2{
3 string localErr = "执行过程中出错,错误信息为:";
4 if (errMsg == null)
5 localErr += "无";
6 else
7 localErr += errMsg;
8
9 string errPageSource = string.Format(ErrorPageTemplate, localErr);
10 HttpContext.Current.Response.Write(errPageSource);
11}
12
2{
3 string localErr = "执行过程中出错,错误信息为:";
4 if (errMsg == null)
5 localErr += "无";
6 else
7 localErr += errMsg;
8
9 string errPageSource = string.Format(ErrorPageTemplate, localErr);
10 HttpContext.Current.Response.Write(errPageSource);
11}
12