永远不会运行OnException方法

时间:2014-06-02 15:39:58

标签: asp.net asp.net-mvc asp.net-mvc-5 asp.net-mvc-filters

我正在构建一个ASP.NET MVC 5 Web应用程序。使用以下内容,我的OnException方法永远不会运行(我无法破解它并且抛出未捕获的异常也没有做任何事情,因此我假设它永远不会运行)

using Elmah;
using System;
using System.Web;
using System.Web.Mvc;

namespace App.WebUI
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new ElmahHandledErrorLoggerFilter());
            filters.Add(new HandleErrorAttribute());
        }
    }

    public class ElmahHandledErrorLoggerFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            // Log only handled exceptions, because all other will be caught by ELMAH anyway.
            if (context.ExceptionHandled)
            {
                ErrorSignal.FromCurrentContext().Raise(context.Exception);
            }
        }
    }
}

这是我的global.asx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace App.WebUI
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

请帮忙。

1 个答案:

答案 0 :(得分:1)

试试这个:

确保您已在root web.config中启用自定义错误。

<system.web>
<customErrors defaultRedirect="~/Error"
                    mode="On">

      </customErrors>
</system.web>

执行此操作后,我已在我的本地ElmahHandledErrorLoggerFilter.OnException执行验证。

我明确地从控制器抛出异常来测试功能。

以下是我的代码:

的TestController:

public ActionResult Index()
        {
            throw new Exception("gone!");
} 

FilterConfig.cs

public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new ElmahHandledErrorLoggerFilter());
            filters.Add(new HandleErrorAttribute());
        }
        public class ElmahHandledErrorLoggerFilter : IExceptionFilter
        {
            public void OnException(ExceptionContext context)
            {
                // Log only handled exceptions, because all other will be caught by ELMAH anyway.
                //it is true
                if (context.ExceptionHandled)
                {
                    var dsf=context.ExceptionHandled;
                }
            }
        }
    }

它可以解决您的问题