将ELMAH日志ID传递给ASP.NET中的自定义错误页面时出现问题

我正在使用ELMAH在ASP.NET Webforms应用程序中记录未处理的exception。 记录工作正常。

我想将ELMAH错误日志ID传递给自定义错误页面,该页面将使用户能够通过电子邮件向管理员发送有关错误的信息。 我听从了这个答案的建议。 这是我的global.asax代码:

 void ErrorLog_Logged(object sender, ErrorLoggedEventArgs args) { Session[StateKeys.ElmahLogId] = args.Entry.Id; // this doesn't work either: // HttpContext.Current.Items[StateKeys.ElmahLogId] = args.Entry.Id; } 

但是,在自定义错误页面上,会话变量引用和HttpContext.Current.Items给了我一个NullReferenceexception。 如何将ID传递给我的自定义错误页面?

这对我有用:

 void ErrorLog_Logged(object sender, ErrorLoggedEventArgs args) { if (args.Entry.Error.Exception is HandledElmahException) return; var config = WebConfigurationManager.OpenWebConfiguration("~"); var customErrorsSection = (CustomErrorsSection)config.GetSection("system.web/customErrors"); if (customErrorsSection != null) { switch (customErrorsSection.Mode) { case CustomErrorsMode.Off: break; case CustomErrorsMode.On: FriendlyErrorTransfer(args.Entry.Id, customErrorsSection.DefaultRedirect); break; case CustomErrorsMode.RemoteOnly: if (!HttpContext.Current.Request.IsLocal) FriendlyErrorTransfer(args.Entry.Id, customErrorsSection.DefaultRedirect); break; default: break; } } } void FriendlyErrorTransfer(string emlahId, string url) { Server.Transfer(String.Format("{0}?id={1}", url, Server.UrlEncode(emlahId))); } 

无法对Ronnie的解决方案发表评论。 我有一段时间,但它打破了标准的错误流程,导致ErrorLog_Logged总是转移,即使在调用时

Elmah.ErrorSignal.FromCurrentContext().Raise(ex);

如果您仍想从catch语句中记录错误,这是一个问题,例如,您有一个错误的解决方法,但想记录错误以执行正确的修复,这对于难以复制的问题非常有帮助。

我能够通过使用以下更改来纠正此问题:

 //if (customErrorsSection != null) if (customErrorsSection != null && this.Context.Error != null) 

这正确地考虑了典型的error handling,因为在你明确地在Elmah中引发exception的情况下context.Error将为null,但在通过默认error handling(不是通过catch或者被捕获并重新抛出)时不是null 。 这导致Ronnie的解决方案响应类似于.Neterror handling逻辑。