ASP.NET MVC 里redirectMode="ResponseRewrite" 時候無法使用 Controller 來設置特定的錯誤頁面。
我做了如下設置:
(1)web.config:
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="Error/defaulterror">
<error statusCode="404" redirect="Error/404"/>
</customErrors>
(2)ErrorController.cs:
public ActionResult Error(string ErrorCode)
{
ViewData["ErrorCOde"] = ErrorCode;
return View();
}
出現下列錯誤:
Server Error in '/' Application.
--------------------------------------------------------------------------------
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /
查詢了資料發現ResponseRewrite的時候系統使用的是Server.Transfer的方式來顯示錯誤信息的。而Server.Transfer與asp.net mv 路由是不兼容的。所以如果使用“ResponseRewrite”的時候defaultRedirect或者 Error tag里的redirect 必須是實際存在的頁面才可以。如下面的配置:
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Common/Error/DefaultError.aspx">
<error statusCode="404" redirect="~/Common/Error/404.aspx"/>
</customErrors>
It is important to note for anyone trying to do this in an MVC application that ResponseRewrite uses Server.Transfer behind the scenes. Therefore, the defaultRedirect must correspond to a legitimate file on the file system. Apparently, Server.Transfer is not compatible with MVC routes, therefore, if your error page is served by a controller action, Server.Transfer is going to look for /Error/Whatever, not find it on the file system, and return a generic 404 error page!
