2012-09-26 145 views
8

我有的捕獲所有異常Global.asax中代碼異常處理ASP.NET MVC

protected void Application_Error(object sender, EventArgs e) 
     { 
      System.Web.HttpContext context = HttpContext.Current; 
      System.Exception exc = context.Server.GetLastError(); 
      var ip = context.Request.ServerVariables["REMOTE_ADDR"]; 
      var url = context.Request.Url.ToString(); 
      var msg = exc.Message.ToString(); 
      var stack = exc.StackTrace.ToString(); 
     } 

我怎樣才能得到控制器名在此錯誤發生

我怎樣才能得到請求客戶IP?

我可以過濾異常嗎?我不需要404,504 .... erors

感謝

+0

'我不需要404,504 .... erors'ehh?這就是HTTP的工作原理。你能用「我可以過濾例外」嗎? – jgauffin

+0

這篇文章肯定會幫助你http://prideparrot.com/blog/archive/2012/5/exception_handling_in_asp_net_mvc – VJAI

回答

6

Global.asax沒有控制器和操作的概念,所以我相信沒有用於檢索控制器和操作名稱的API。然而,你可能會給一個嘗試解決請求的URL:

HttpContextBase currentContext = new HttpContextWrapper(HttpContext.Current); 
UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext); 
RouteData routeData = urlHelper.RouteCollection.GetRouteData(currentContext); 
string action = routeData.Values["action"] as string; 
string controller = routeData.Values["controller"] as string; 

,以獲取用戶IP您可以使用UserHostAddress屬性:

string userIP = HttpContext.Current.Request.UserHostAddress; 

要過濾掉HTTP,你是不是要處理,你可以例外使用類似:

HttpException httpException = exception as HttpException; 
if (httpException != null) 
{ 
    switch (httpException.GetHttpCode()) 
    { 
     case 404: 
     case 504: 
      return; 
    } 
} 

一個關於例外處理最後那句話 - 這是不這樣做在全球範圍內時,有進行更LOC的方式最佳實踐盟友。例如,在ASP.NET MVC基地Controller類有一個方法:

protected virtual void OnException(ExceptionContext filterContext) 

其中,重寫時,會給你上發生的異常的完全控制。你可以擁有一切可供您在Global.asax中 ASP.NET MVC特定的功能,如引用到控制器,視圖上下文,路線數據等信息

+0

Andrei感謝你完美地重播你的代碼。你能提供一些關於基礎控制器類的好教程嗎? –

+0

@酸,當然。有關基本示例,請查看[博客文章](http://www.entwicklungsgedanken.de/2009/07/16/redirect-from-the-onexception-method-inside-the-controller-with-asp-net-mvc /)和這[文章](http://www.devproconnections.com/article/aspnetmvc/aspnet-exception-141263)。 – Andrei

+0

您可以跳過使用UrlHelper用法(並跳過MVC參考)......'RouteData routeData = System.Web.Routing.RouteTable.Routes.GetRouteData(currentContext);' –

3

我像這樣使用它的下面

,你可以得到用戶的IP這樣

var userip = context.Request.UserAgent; 

,你可以得到你的網址發生此類錯誤的原因如下

var ururl = System.Web.HttpContext.Current.Request.Url; 

我認爲這會幫助你......

0

我會採取不同的策略,並把使用控制器上的屬性(或基本控制器,如果有的話)

public class HandleErrorAttributeCustom : HandleErrorAttribute 
    { 
     public override void OnException(ExceptionContext context) 
     { 
      //you can get controller by using 
      context.Controller.GetType() 

      //however, I'd recommend pluggin in Elmah here instead 
      //as it gives this easily and also can has filtering 
      //options that you want 

     } 
}