2014-02-10 119 views
0

我已經修改了我的路由,以包括在MVC錯誤頁面控制器和自定義路由

routes.MapRoute(
      name: "Default", 
      url: "{culture}/{controller}/{action}/{id}", 
      defaults: new { culture = "en-GB", controller = "StyleGuide", action = "Template", id = UrlParameter.Optional }, 
      constraints: new { culture = @"[a-z]{2}-[A-Z]{2}" } 
     ); 

我也曾在Web.config創建ErrorController和定義我的錯誤頁的URL文化:

<customErrors mode="On" defaultRedirect="~/Error/Index"> 
    <error statusCode="404" redirect="~/Error/NotFound"/> 
</customErrors> 

我我也使用mvcSiteMapProvider,所以我已經包含了我的新錯誤頁面,並且能夠通過菜單訪問它們,因爲它使用包含我的文化的URL:localhost/en-GB/Error/NotFound

當拋出異常時,錯誤頁面未找到,因爲Web.Config中定義的重定向缺少文化。

如何在重定向到錯誤頁面時包含文化?

回答

-1

這是記述有關ASP.NET MVC的錯誤處理方法的可能性和侷限性的好文章:Exception Handling in ASP.NET MVC

如果您不需要控制器或行動水平的異常處理,你可以做錯誤處理Application_Error事件。您可以關閉web.config中的自定義錯誤,並在此事件中執行日誌記錄和錯誤處理(包括重定向到正確的頁面)。

東西相似:

protected void Application_Error(object sender, EventArgs e) 
{ 
    Exception exception = Server.GetLastError(); 
    Response.Clear(); 

    HttpException httpException = exception as HttpException; 

    string action = string.Empty;  

    if (httpException != null) 
    { 
     switch (httpException.GetHttpCode()) 
     { 
      case 404: 
       // page not found 
       action = "NotFound"; 
       break; 
      //TODO: handle other codes 
      default: 
       action = "general-error"; 
       break; 
     } 
    } 
    else 
    { 
     //TODO: Define action for other exception types 
     action = "general-error"; 
    } 

    Server.ClearError(); 

    string culture = Thread.CurrentThread.CurrentCulture.Name;  

    Exception exception = Server.GetLastError(); 
    Response.Redirect(String.Format("~/{0}/error/{1}", culture, action)); 
} 
+0

我會很快看一下這一點,並儘快給您 - 感謝您的回答! –

+1

感謝您及時回覆他們 – nathanchere