问题通过ELMAH日志ID为自定义错误页在ASP.NET自定义、错误、问题、日志

2023-09-02 21:11:53 作者:共偕老

我使用 ELMAH 来记录未处理在ASP.NET Web表单应用程序异常。日志记录工作正常。

I am using ELMAH to log unhandled exceptions in an ASP.NET Webforms application. Logging is working fine.

我要的ELMAH错误日志ID传递给自定义错误页,这将使用户能够通过电子邮件发送有关错误管理员的能力。我按照意见this回答。这是我的的Global.asax code:

I want to pass the ELMAH error log id to a custom error page that will give the user the ability to email an administrator about the error. I have followed the advice from this answer. Here is my global.asax code:

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来我的自定义错误页?

But, on the Custom error page, the session variable reference and HttpContext.Current.Items are giving me a NullReference exception. How can I pass the ID to my custom error page?

推荐答案

这对我的作品:

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