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

时间:2010-05-21 20:52:30

标签: c# .net visual-studio elmah

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

我想将ELMAH错误日志ID传递给自定义错误页面,该页面将使用户能够通过电子邮件向管理员发送有关错误的信息。我遵循了this answer的建议。这是我的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给了我一个NullReference异常。如何将ID传递给我的自定义错误页面?

2 个答案:

答案 0 :(得分:7)

这对我有用:

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)));
}

答案 1 :(得分:2)

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

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

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

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

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

这正确地考虑了典型的错误处理,因为在你明确地在Elmah中引发异常的情况下context.Error将为null,但在通过默认错误处理(不通过catch或者如果被捕获并且重新获取)时不为null -thrown)。这导致Ronnie的解决方案响应类似于.Net错误处理逻辑。

相关问题