Asp.Net customErrors与httpErrors的区别

先看一下简单的对比

customErrors

  • Asp.Net级别的错误处理程序,只处理Asp.Net应用抛出的异常(404,403,500。。)
  • 在IIS7+的服务器依然可用(IIS7之前就引进了)
  • 静态文件(如.jpg.htm.js等)不会被处理

httpErrors

  • IIS级别的错误信息处理程序,IIS根据请求指定错误页面
  • 自IIS7引进
  • 处理包括ASP.NET应用及ASP.NET之外的应用(ASP.NET能管的 它会管,ASP.NET不能管得它也管)
  • 所有的文件和URL都处理

从对比中能看出 在IIS7之后  就没必要再用customErrors了,一切httpErrors都可以办了。

<httpErrors errorMode="Custom" existingResponse="Replace">
    <remove statusCode="403" subStatusCode="-1" />
    <remove statusCode="404" subStatusCode="-1" />
    <error statusCode="403" prefixLanguageFilePath="" path="/403.png" responseMode="ExecuteURL" />
    <error statusCode="404" path="/404.aspx" responseMode="ExecuteURL" /> 
</httpErrors>

其实还可以用一个clear标签代替多个remove。如下

<httpErrors errorMode="Custom" existingResponse="Replace">
    <clear />
    <error statusCode="403" prefixLanguageFilePath="" path="/403.png" responseMode="ExecuteURL" />
    <error statusCode="404" path="/404.aspx" responseMode="ExecuteURL" /> 
</httpErrors>

Note:ExecuteURL 只能用于同一个应用下的ASP.NET文件,如果想要重定向到另一个应用,或者一个完全不一样的完整的URL,我们需要将responseMode设为Redirect。

<httpErrors errorMode="Custom" existingResponse="Replace">
  <clear />
  <error statusCode="404" path="http://www.bing.com" responseMode="Redirect"/>
</httpErrors>

现在通过不同的URL来看两者的区别

给Web应用定义如下配置

 <system.web>
    <customErrors mode="On" defaultRedirect="Error.html">
        <error statusCode="403" redirect="/Error403" />
        <error statusCode="404" redirect="/Error404" />
        <error statusCode="500" redirect="/Error500" />
    </customErrors>
</system.web>
<system.webServer>
  <httpErrors errorMode="Custom" existingResponse="Auto" defaultResponseMode="ExecuteURL" >
    <remove statusCode="403"/>
    <remove statusCode="404"/>
    <remove statusCode="500"/>
    <error statusCode="403" responseMode="ExecuteURL" path="/Error403" />
    <error statusCode="404" responseMode="ExecuteURL" path="/Error404" />
    <error statusCode="500" responseMode="ExecuteURL" path="/Error500" />
  </httpErrors>
</system.webServer>

现在如果尝试访问以下链接,将会产生对应的错误

 
URL Error StatusCode
/aaaaaa  httpErrors  404
/aaaaaa.aspx customErrors  404
/aaaaaa.jpg httpErrors  404
/throw500.apx customErrors  500
/throw500 customErrors  500

  1. 一般情况 customErrors标签上的model属性设为RemoteOnly,httpErrors上的errorModel设为DetailedLocalOnly
  2. 如果你将某个页面的StatusCode设为500,不要忘了设置如下属性
    context.Response.TrySkipIisCustomErrors = true;

 相关参考:

Custom 404 and error pages in ASP.NET

IIS.NET  HTTP Errors

原文地址:https://www.cnblogs.com/TiestoRay/p/4723996.html