我跟着this post并创建了一个全局错误处理程序。我自己添加了处理404错误。但是,当我在本地测试时它工作正常但是一旦部署到Web服务器,我的自定义消息就不再显示了。相反,默认丑陋的显示出来。
在远程调试中,我可以跟踪执行情况,它确实可以进入我的自定义404错误操作,但不知何故,IIS在某些时候接管了。
在我的Global.asax.cs中,我有:
protected void Application_Error()
{
var exception = Server.GetLastError();
var httpException = exception as HttpException;
Response.Clear();
Server.ClearError();
var routeData = new RouteData();
routeData.Values["controller"] = "Error";
routeData.Values["action"] = "General";
routeData.Values["exception"] = exception;
Response.StatusCode = 500;
if (httpException != null)
{
Response.StatusCode = httpException.GetHttpCode();
switch (Response.StatusCode)
{
case 403:
routeData.Values["action"] = "Http403";
break;
case 404:
routeData.Values["action"] = "Http404";
break;
}
}
IController errorController = new ErrorController();
var rc = new RequestContext(new HttpContextWrapper(Context), routeData);
errorController.Execute(rc);
}
然后在我的ErrorHandler.cs中,我有:
public ActionResult General(Exception exception)
{
// log error
return Content("General error", "text/html");
}
public ActionResult Http403(Exception exception)
{
return Content("Forbidden", "text/plain");
}
public ActionResult Http404(Exception exception)
{
return Content("Page not found.", "text/plain"); // this displays when tested locally, but not after deployed to web server.
}
}
答案 0 :(得分:8)
你是对的,远程IIS正在接管你的404页面。您需要告诉IIS跳过自定义错误设置Response.TrySkipIisCustomErrors = true;
所以你的代码应该是这样的。
protected void Application_Error()
{
//...
Response.TrySkipIisCustomErrors = true;
Response.StatusCode = 404;
//...rest of your code
}
另请查看此链接以获取更多信息http://www.west-wind.com/weblog/posts/2009/Apr/29/IIS-7-Error-Pages-taking-over-500-Errors