以前使用Global.asax记录全局的错误日志觉得挺好用,但是如果一个解决方案下有N多个项目,每个下边都需要加一个并且代码都还是重复的,终于有一天无法再忍受这种模式,考虑到HttpModule,直接上代码
CS代码如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web;
namespace HttpModuleTest { /// <summary> /// /// </summary> public class CommonHttpModule : IHttpModule { public void Init(HttpApplication context) { context.Error += Request_Error; } /// <summary> /// 全局错误日志 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void Request_Error(object sender, EventArgs e) { if (string.Equals(ConfigurationUtil.GetAppSettingValue("Debug"), "true", StringComparison.OrdinalIgnoreCase)) return; var application = sender as HttpApplication; if (Equals(application, null)) return; string requestUrl = application.Request.Url.AbsolutePath; Exception appError = HttpContext.Current.Server.GetLastError(); //todo: 对错误日志进行记录 文本记录OR入库 自己选择 application.Server.ClearError(); //为了仿止URL跳转循环,一般不会出现,加上更保险 if (!string.Equals(requestUrl, "/Error.aspx", StringComparison.OrdinalIgnoreCase)) //跳转的公共错误页 application.Response.Redirect("/Error.aspx"); } public void Dispose() { } } }
Web.config配置如下:
<system.webServer> <modules runAllManagedModulesForAllRequests="true"> <add name="CommonHttpModule" type="HttpModuleTest.CommonHttpModule"/> </modules> </system.webServer>