2013-11-01 15 views
0

我試圖將訪問的URL傳遞給我的錯誤控制器,名爲ErrorController,以便我可以記錄當時正在訪問的頁面。將當前網址與routedata傳遞到自定義錯誤控制器

在我的Global.asax.cs我有一個方法Application_Error看起來像這樣:

protected void Application_Error(object sender, EventArgs e) 
{ 
    var httpContext = ((MvcApplication)sender).Context; 

    var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext)); 
    var currentController = " "; 
    var currentAction = " "; 

    if (currentRouteData != null) 
    { 
     if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString())) 
     { 
      currentController = currentRouteData.Values["controller"].ToString(); 
     } 

     if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString())) 
     { 
      currentAction = currentRouteData.Values["action"].ToString(); 
     } 
    } 

    var ex = Server.GetLastError(); 

    var controller = new ErrorController(); 
    var routeData = new RouteData(); 
    var action = "Index"; 

    if (ex is HttpException) 
    { 
     var httpEx = ex as HttpException; 

     switch (httpEx.GetHttpCode()) 
     { 
      case 404: 
       action = "NotFound"; 
       // Pass along some data about accessed page here 
       break; 

      // others if any 

      default: 
       action = "Index"; 
       break; 
     } 
    } 

    httpContext.ClearError(); 
    httpContext.Response.Clear(); 
    httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : 500; 
    httpContext.Response.TrySkipIisCustomErrors = true; 
    routeData.Values["controller"] = "Error"; 
    routeData.Values["action"] = action; 

    controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction); 
    ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData)); 
} 

而且我ErrorController看起來是這樣的:

public class ErrorController : BaseController 
{ 
    private readonly ILog _logger; 
    public ErrorController() 
    { 
     _logger = LogManager.GetLogger("CustomHandleErrorAttribute.class"); 
    } 

    // 
    // GET: /Error/ 

    public ActionResult Index() 
    { 
     return View(); 
    } 

    public ActionResult NotFound(string error) 
    { 
     _logger.Error(error); 
     return View(); 
    } 
} 

我應該如何去填充錯誤參數所以我可以將其記錄到我的文件中?

回答

0

落得這樣做在我的ErrorController.cs如下:

if (Request.Url != null) 
{ 
    var path = Request.Url.AbsoluteUri; 
    _logger.Error("404: " + path); 
} 
0

我認爲你已經完成了一些複雜化。只需創建一個共享函數,在您的錯誤控制器類中記錄異常和頁面。這樣你就可以忘記一起佈線。您可以使用請求上的UrlReferrer屬性來獲取發生錯誤的頁面。

的Global.asax(vb.net):

Sub Application_Error() 

    Dim ex As Exception = Server.GetLastError() 
    Dim page As String = If(Not IsNothing(Request), Request.UrlReferrer.AbsoluteUri, Nothing) 
    ErrorController.LogError(ex, page) 

    Server.ClearError() 

End Sub 
相關問題