4

我有一个在 .NET 4.0 上运行的 ASP.NET MVC 站点,我正在尝试设置错误日志记录。

我发现了 Elmah.MVC NuGet 包(v2.1.1,Elmah 核心:v1.2.1)并按照本教程进行设置。(没有做第 5 步 - javascript 错误记录)

它工作正常并向我发送电子邮件并记录 404 错误,但是当我在输入中输入一些 html<h1>Test</h1>以查看站点如何处理它时,我得到一个 HttpRequestValidationException ,这在某种意义上很好,因为它不会让他们输入它而且我有一个网站发布时显示的错误页面设置,但 Elmah 不会记录此类错误的详细信息。

我看过这个 SO 帖子Elmah 问题 217说它已经解决了。

这是我的 ElmahHandleErrorAttribute 类:

public class ElmahHandleErrorAttribute : System.Web.Mvc.HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        base.OnException(context);

        var e = context.Exception;

// Log only handled exceptions, because all other will be caught by ELMAH anyway.
// from http://ivanz.com/2011/05/08/asp-net-mvc-magical-error-logging-with-elmah/
// did nothing
        // if (context.ExceptionHandled)
        //    ErrorSignal.FromCurrentContext().Raise(context.Exception);

        if (!context.ExceptionHandled   // if unhandled, will be logged anyhow
            || RaiseErrorSignal(e)      // prefer signaling, if possible
            || IsFiltered(context))     // filtered?
            return;

        LogException(e);
    }

    private static bool RaiseErrorSignal(Exception e)
    {
        var context = HttpContext.Current;
        if (context == null)
            return false;
        var signal = ErrorSignal.FromContext(context);
        if (signal == null)
            return false;
        signal.Raise(e, context);
        return true;
    }

    private static bool IsFiltered(ExceptionContext context)
    {
        var config = context.HttpContext.GetSection("elmah/errorFilter")
                     as ErrorFilterConfiguration;

        if (config == null)
            return false;

        var testContext = new ErrorFilterModule.AssertionHelperContext(
                                  context.Exception, HttpContext.Current);

        return config.Assertion.Test(testContext);
    }

    private static void LogException(Exception e)
    {
        var context = HttpContext.Current;
        ErrorLog.GetDefault(context).Log(new Error(e, context));
    }
}

我在我的FilterConfig.cs

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new ElmahHandleErrorAttribute());
    filters.Add(new HandleErrorAttribute());

}

是否有已知的解决方法,以便我可以让 Elmah 记录这些类型的错误并通过电子邮件发送详细信息?

谢谢。

4

1 回答 1

2

这个问题似乎与 ASP.NET 4 中的重大变化有关,请参阅:此链接此链接

这是我如何让它工作的:

        if (HttpContext.Current != null)
            Elmah.ErrorLog.GetDefault(HttpContext.Current).Log(new Elmah.Error(e));
        else 
            ErrorSignal.FromCurrentContext().Raise(e);

不知何故,“Elmah.ErrorLog.GetDefault(HttpContext.Current).Log()”方法有效。

于 2016-06-23T12:26:25.133 回答