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

Ron*_*rby 6 .net c# elmah visual-studio

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

我想将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;
}
Run Code Online (Sandbox Code Playgroud)

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

Ron*_*rby 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)));
}
Run Code Online (Sandbox Code Playgroud)

  • 您是否曾使用`Server.Transfer`获得"执行子请求错误..."? (4认同)
  • `HandledElmahException`是你的答案[here](http://stackoverflow.com/a/2906221/39396)中描述的自定义类 (2认同)