ASP.NET MVC ELMAH无法记录HttpRequestValidationExceptions

4
我有一个运行在.NET 4.0上的ASP.NET MVC站点,我正在尝试设置错误日志记录。我发现了Elmah.MVC NuGet包(v2.1.1,Elmah核心:v1.2.1),并按照此教程this tutorial进行设置。(没有执行第5步- javascript错误日志记录)。它正常工作并向我发送电子邮件和记录404错误,但是当我输入一些html到输入框<h1>Test</h1>以查看网站如何处理它时,我会得到一个HttpRequestValidationException异常,这在某种意义上很好,因为它不会让他们输入它,并且我已经设置了一个错误页面,在网站发布后显示,但是Elmah不会记录此类错误的详细信息。我查看了this SO postElmah issue 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 记录并发送这些错误的详细信息?谢谢。
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()”方法能够工作。

这些链接和我已经查看过的链接完全相同:)。不过还是谢谢你提供的解决方法! - Jake
@Jake 哦!我没意识到链接是一样的。我一直在寻找解决问题的方法,浏览了很多页面。我肯定是在某个地方迷路了 :$ - Veysel Ozdemir

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接