用于 ASP.NET 错误处理的 HTTP 模块






3.71/5 (9投票s)
2006年10月31日
1分钟阅读

152904

1055
这是一个简单的 HTTP 模块,用作 ASP.NET 应用程序的“最后的手段”错误处理程序。它不需要更改现有代码,并且可以“直接插入”到已经运行的站点中。
引言
我为一位客户编写了这个 HTTP 模块,以便将其插入到正在进行集成测试的现有站点中,该站点出现间歇性错误。客户想要一个能够捕获基本错误信息以及请求查询字符串/表单参数并将其写出的程序。所有这些都需要在不修改现有代码的情况下完成。
虽然现有代码在代码隐藏文件中确实有常规的 try
-catch
错误处理程序,但并非所有错误都得到正确处理,并且在某些情况下,catch
块中的代码本身也容易出错。最初,我考虑使用自定义错误页面。但是,考虑到获取正确错误上下文的问题,我决定使用 HTTP 模块。
代码
代码本身非常简单明了。
第一步是为 Error
事件绑定一个事件处理程序
public void Init (HttpApplication app)
{
app.Error += new System.EventHandler (OnError);
}
第二步是编写实际的事件处理程序,以写出错误消息和请求表单/查询字符串参数
public void OnError (object obj, EventArgs args)
{
// At this point we have information about the error
HttpContext ctx = HttpContext.Current;
HttpResponse response = ctx.Response;
HttpRequest request = ctx.Request;
Exception exception = ctx.Server.GetLastError();
response.Write("Your request could not processed. " +
"Please press the back button on" +
" your browser and try again.<br/>");
response.Write("If the problem persists, please " +
"contact technical support<p/>");
response.Write("Information below is for " +
"technical support:<p/>");
string errorInfo = "<p/>URL: " + ctx.Request.Url.ToString ();
errorInfo += "<p/>Stacktrace:---<br/>" +
exception.InnerException.StackTrace.ToString();
errorInfo += "<p/>Error Message:<br/>" +
exception.InnerException.Message;
//Write out the query string
response.Write("Querystring:<p/>");
for(int i=0;i<request.QueryString.Count;i++)
{
response.Write("<br/>" +
request.QueryString.Keys[i].ToString() + " :--" +
request.QueryString[i].ToString() + "--<br/>");// + nvc.
}
//Write out the form collection
response.Write("<p>---------------" +
"----------<p/>Form:<p/>");
for(int i=0;i<request.Form.Count;i++)
{
response.Write("<br/>" +
request.Form.Keys[i].ToString() +
" :--" + request.Form[i].ToString() +
"--<br/>");// + nvc.
}
response.Write("<p>-----------------" +
"--------<p/>ErrorInfo:<p/>");
response.Write (errorInfo);
// --------------------------------------------------
// To let the page finish running we clear the error
// --------------------------------------------------
ctx.Server.ClearError ();
}
部署
要部署此 HTTP 模块,只需将编译后的 DLL 放入 bin 文件夹,并在 web.config 中进行以下条目以注册它
<system.web>
<!-- Add the lines below to register the http module -->
<httpModules>
<add type="MyApps.Utilities.GlobalErrorHandler,
GlobalErrorHandler"
name="GlobalErrorHandler" />
</httpModules>
</system.web>
下载
您可以从上面的链接下载完整的源代码(.cs 文件)、一个示例 web.config 以及编译后的 DLL,它们在一个名为 GlobalErrorHandler.zip 的 zip 文件中。
进一步改进
这段代码实际上是几个小时的工作成果,因此显然可以对其进行改进。我目前正在考虑的一些更改:使显示文本动态化,并通过 web.config 使整体显示更具可定制性。此外,选择发送电子邮件或记录错误消息将很有用。我将在未来几周内发布更新后的代码。