2010-08-02 29 views

回答

2

使用標準的ASP.NET錯誤頁面(在web.config中激活):

<customErrors mode="On|RemoteOnly" defaultRedirect="/error/problem"> 
    <error statusCode="404" redirect="/error/notfound"/> 
    <error statusCode="500" redirect="/error/problem"/> 
</customErrors> 

和/或創建一個錯誤處理控制器和一個包羅萬象的路線使用它:

ErrorController.cs :

public class ErrorController : Controller 
{ 
    public ActionResult NotFound(string aspxerrorpath) 
    { 
     // probably you'd like to log the missing url. "aspxerrorpath" is automatically added to the query string when using standard ASP.NET custom errors 
     // _logger.Log(aspxerrorpath); 
     return View(); 
    } 
} 

的Global.asax:

// This route catches all urls that do not match any of the previous routes. 
// So if you registered the standard routes, somthing like "/foo/bar/baz" will 
// match the "{controller}/{action}/{id}" route, even if no FooController exists 
routes.MapRoute(
    "Catchall", 
    "{*catchall}", 
    new { controller = "Error", action = "NotFound" } 
); 
+0

我已經添加了routes.MapRoute(),它不起作用。任何想法爲什麼?我已經制作了控制器和視圖。 – 2010-08-02 02:13:47

+0

Catchall路線只會捕捉與其他路線不匹配的路線。因此,如果您擁有標準路線「{controller}/{action}/{id}」,即使沒有FooController存在,每個看起來像這樣的「/ foo/bar/baz」的Url都將匹配該路線。 爲了捕獲所有缺少的控制器/操作,最簡單的解決方案是使用ASP.NET自定義錯誤。你要麼爲錯誤頁面使用靜態文件,要麼爲此創建一個控制器/操作(使用上面的示例將重定向到ErrorController並調用NotFound操作)。我編輯了我的答案,以包括這一點。 – davehauser 2010-08-02 11:04:57

+0

有關此主題的更多詳細信息,請參閱以下問題:http://stackoverflow.com/questions/619895/how-can-i-properly-handle-404s-in-asp-net-mvc/2577095#2577095 – davehauser 2010-08-04 13:01:03

相關問題