<customErrors mode="On"><error code="404" path="404.html" /><error code="500" path="500.html" /></customErrors>自定义404错误页面
<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"/><title>404 Page Not Found</title></head><body><h1>404 Page Not Found</h1></body></html>我创建了一个新的ASP.NET MVC 5应用程序,包含vs自带的标准模版。如果我运行它尝试导航到一个不存在的路径 e.g. /foo/bar,就会得到一个包含如下信息的标准 ASP.NET 404 页面:、
不太友好不是?
这种情况的错误是由ASP.NET MVC引发因为它没有找到与url相匹配的controller或action。
为了自定义404错误页面,在web.config 的 <system.web></system.web>配置节:
<customErrors mode="On"> <error statusCode="404" redirect="~/404.html"/></customErrors>mode="On" 这样我们就能在本地看到错误页面。一般你可能只想在投入使用时呈现而设置为 mode="RemoteOnly"。
<customErrors mode="On" redirectMode="ResponseRewrite"> <error statusCode="404" redirect="~/404.html"/></customErrors>然而这并没有太大的作用(这老外真啰嗦).尽管原Url地址没有被重定向, ASP.NET 仍然返回的是 200,此外将我们自定义错误页显示为纯文本。
<httpErrors errorMode="Custom"> <remove statusCode="404"/> <error statusCode="404" path="/404.html" responseMode="ExecuteURL"/></httpErrors>同样设置 errorMode="Custom" 以便本地测试. 正常情况会设置为 errorMode="DetailedLocalOnly".
<customErrors mode="On" redirectMode="ResponseRewrite"> <error statusCode="404" redirect="~/404.aspx"/> <error statusCode="500" redirect="~/500.aspx"/></customErrors>类似于前面创建的404.aspx:
<% Response.StatusCode = 500 %><!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><title>500 Server Error</title></head><body><h1>500 Server Error</h1></body></html>不幸的是这样做并不会捕获到你应用程序中的每一个异常。一个相当常见的错误——由 ASP.NET 产生的请求的验证,如一个危险的url路径/foo/bar<script></script> ,这个实际上会产生一个404响应;因此你可以添加一个默认错误配置:
<customErrors mode="Off" redirectMode="ResponseRewrite" defaultRedirect="~/500.aspx"> <error statusCode="404" redirect="~/404.aspx"/> <error statusCode="500" redirect="~/500.aspx"/></customErrors>最后为了捕获非ASP.NET异常我们设置IIS自定义服务器内部错误500错误页面:
<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite" defaultRedirect="~/500.aspx"> <error statusCode="404" redirect="~/404.aspx"/> <error statusCode="500" redirect="~/500.aspx"/></customErrors>配置IIS自定义错误页:
<httpErrors errorMode="DetailedLocalOnly"> <remove statusCode="404"/> <error statusCode="404" path="404.html" responseMode="File"/> <remove statusCode="500"/> <error statusCode="500" path="500.html" responseMode="File"/></httpErrors>原文链接:http://benfoster.io/blog/aspnet-mvc-custom-error-pages