覆盖虚拟主机的默认错误页面
问题描述:
我刚刚发布了一个ASP.NET MVC网站,我在其中构建了自定义错误页面。下面是我如何实现它们:覆盖虚拟主机的默认错误页面
在ErrorController:
在web.config中:
<customErrors mode="On" defaultRedirect="~/500">
<error statusCode="403" redirect="~/403"/>
<error statusCode="401" redirect="~/401"/>
<error statusCode="404" redirect="~/404"/>
<error statusCode="409" redirect="~/409"/>
<error statusCode="500" redirect="~/500"/></customErrors>
当然,错误的请求路由到NOTFOUND方法,等等。理论上,它应该起作用。
但是,我面临一个问题:现在,我已将我的网站发布给我的主机(GoDaddy),我注意到返回HTTP状态的错误代码会导致我的自定义错误页面被默认GoDaddy的。
我该如何解决这个问题?当然,最简单的解决方案是返回200状态码,但我更愿意返回真正的错误代码(对于SEO等)。
答
你应该问GoDaddy这件事。这不是一个ASP.NET MVC问题。如果他们劫持所有不同于200的状态码来显示他们自己的错误页面,那么你不能做太多事情。
答
你应该为每一个状态代码创建自定义的ViewResult并重写这样
public class NotFoundViewResult : ViewResult
{
public NotFoundViewResult()
{
ViewName = "404";
}
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
response.StatusCode = 404;
// This will prevent IIS7 (GoDaddy) from overwriting your error page!
response.TrySkipIisCustomErrors = true;
base.ExecuteResult(context);
}
}
它的ExecuteReuslt方法你的404视图应该被共享的文件夹中,以便每个人都可以访问它,你的ErrorController现在看起来应该是这样
public ActionResult NotFound()
{
return new NotFoundViewResult();
}
+1提醒response.TrySkipIisCustomErrors - http://*.com/questions/1706934/asp-net-mvc-app-custom-error-pages-not-displaying-in-shared-hosting-environment has一个更详细的答案和链接到Rick Strahl博客上的有用条目 - http://www.west-wind.com/weblog/posts/745738.aspx – KevD 2012-11-06 11:02:29