2013-07-03 22 views
6

我無法獲得在我的MVC4應用程序中使用的自定義HandleErrorAttribute。MVC4自定義HandleErrorAttribute,global.asax中的方法不叫

自定義類記錄異常

public class HandleAndLogErrorAttribute : HandleErrorAttribute 
    { 
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); 

    public override void OnException(ExceptionContext filterContext) 
    { 
     var message = string.Format("Exception  : {0}\n" + 
            "InnerException: {1}", 
            filterContext.Exception, 
            filterContext.Exception.InnerException); 
     Logger.Error(message); 
     base.OnException(filterContext); 
    } 
    } 

在Global.asax中我添加了一個新的靜態方法:

public class MvcApplication : System.Web.HttpApplication 
    { 
    protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 

     WebApiConfig.Register(GlobalConfiguration.Configuration); 
     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
    } 

    public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
    { 
     filters.Add(new HandleAndLogErrorAttribute()); //Todo: log all errors 
     throw new Exception("not called???"); 
    } 

    } 

當一個異常被拋出,error.chstml被加載,但自定義HandlErrorAttribute中的OnException重寫永遠不會被調用。

我懷疑Global.asax中的RegisterGlobalFilters方法沒有被調用,並且在那裏拋出一個異常(見代碼)證實了這一點。這個例外從不拋出。

在我設置的customErrors在web.config文件:

<customErrors mode="On"> 
</customErrors> 

我用另一種解決方案相同的方法,我不明白爲什麼這HandleErrorAttribute擴展不工作。

回答

9

您在Global.asax中創建了RegisterGlobalFilters方法,但自從MVC 4以來,全局過濾器註冊在App_Start/FilterConfig.cs的單獨文件中指定。

您的Global.asax中的行FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters)正在調用指定文件中定義的註冊。

將您的自定義過濾器註冊添加到指定的文件,或手動調用您的(本地)RegisterGlobalFiltersApplication_Start

+0

這與MVC3有何不同?因爲我相信我在那裏成功地使用了相同的方法。謝謝你的答案! – Kman

+0

是的,它不同於MVC3。它有意義,它爲你工作,因爲這是註冊過濾器的常規方法,將它們添加到'Global.asax'中定義的'public static void RegisterGlobalFilters'中。 – haim770

+0

@ haim770,如果你在你的方法RegisterGlobalFilters上使用'Find references',你會發現它沒有被任何代碼引用。無論MVC版本如何,情況都是如此。 – MEMark