2012-04-17 67 views
1

我想知道是否有可能在不修改web.config或global.asax文件的情況下捕獲未處理的錯誤。捕獲ASP.NET MVC錯誤和WebActivator

理想的情況下我會使用WebActivator包,有這樣的事情:

[assembly: WebActivator.PostApplicationStartMethod(typeof(MyProject.Initialize), "Start")] 

namespace MyProject 
{ 
    using System; 
    using System.Collections.Generic; 
    using System.Web; 
    using System.Web.Mvc; 

    internal static Initialize 
    { 
     public static void Start() 
     { 
       // this doesn't work 
       HttpContext.Current.ApplicationInstance.Error += ApplicationInstance_Error; 
     } 

     // this never fires 
     static void ApplicationInstance_Error(object sender, EventArgs e) 
     { 
      throw new NotImplementedException(); 
     } 
    } 
} 

問題1:是否可以捕捉未處理的錯誤,而無需修改的web.config或Global.asax中的文件?

問題2:怎麼樣?

更新:我在下面發佈了一個答案。我不確定這是否是最好的方法。任何意見讚賞。

回答

0

我能得到的東西使用這種方法的工作:

[assembly: WebActivator.PreApplicationStartMethod(typeof(MyProject.Initialize), "Start")] 

namespace MyProject 
{ 
    using System; 
    using System.Collections.Generic; 
    using System.Web; 
    using System.Web.Mvc; 

    internal static Initialize 
    { 
     public static void Start() 
     { 
      GlobalFilters.Filters.Add(new WatchExceptionAttribute()); 
     } 
    } 

    public class CustomHandleErrorAttribute : HandleErrorAttribute 
    { 
     public override void OnException(ExceptionContext filterContext) 
     { 
      // do your thing here. 
     } 
    } 
} 
+0

該解決方案犯規解決錯誤404 HandleErrorAttribute的等主要目的是處理內部未處理例外。 – 2015-10-07 21:23:53

0

請參見下面的MSDN博客:HandleError

+0

這似乎是在這裏提供的相同的答案:http://stackoverflow.com/a/10184264/504836有什麼新的,我錯過了? – joelnet 2012-04-18 21:10:16