Asp.net

如何將所有 httpErrors 重定向到自定義 url?

  • January 18, 2016

這些是 web.config 中的程式碼:

<system.web>
 <customErrors mode="Off" >
 </customErrors>
</system.web>
<system.webServer>
 <httpErrors errorMode="Custom" existingResponse="Replace">
   <clear />
   <error statusCode="404" prefixLanguageFilePath="" path="/ResourceNotFound" responseMode="ExecuteURL" />
   <error statusCode="500" prefixLanguageFilePath="" path="/ResourceNotFound" responseMode="ExecuteURL" />
   </httpErrors>
</system.webServer>

以上設置將僅重定向 404 和 500 的 httpError。

但不是手動添加所有錯誤程式碼 400, 401, 403….etc..etc…

我們可以將其設置為將所有錯誤重定向到相同的 url 而無需輸入所有錯誤程式碼嗎?

<error statusCode="400" .....
<error statusCode="401" .....
<error statusCode="403" .....
<error statusCode="404" .....
<error statusCode="xxx" ....

嘗試這個,

添加 web.config 文件。

<system.webServer>
 <httpErrors errorMode="DetailedLocalOnly" defaultResponseMode="File" >
   <remove statusCode="500" />
   <error statusCode="500" prefixLanguageFilePath="C:\Contoso\Content\errors"
   path="500.htm" />
</httpErrors>
</system.webServer>

<httpErrors existingResponse="Replace" defaultResponseMode="ExecuteURL" errorMode="Custom">
   <remove statusCode="404" />
   <error statusCode="404" path="/ErrorPages/Oops.aspx" responseMode="ExecuteURL"/>
   <remove statusCode="401" />
   <error statusCode="401" path="/Account/Login.aspx" responseMode="ExecuteURL"/>
   <remove statusCode="501"/>
   <error statusCode="501" path="/ErrorPages/Oops.aspx" responseMode="ExecuteURL"/>
   <remove statusCode="411"/>
   <error statusCode="411" path="/ErrorPages/Oops.aspx" responseMode="ExecuteURL"/>
   <remove statusCode="403"/>
   <error statusCode="403" path="/ErrorPages/Oops.aspx" responseMode="ExecuteURL"/>
</httpErrors>

以及有關此http://www.iis.net/configreference/system.webserver/httperrors的更多資訊

httpErrors部分具有defaultPath屬性。

<system.webServer>
 <httpErrors defaultPath="Error.html" defaultResponseMode="File">
   <clear />
 </httpErrors>
</system.webServer>

http://www.iis.net/configreference/system.webserver/httperrors

但是,我不使用它,因為defaultPath預設情況下被鎖定在 IIS Express 中。需要編輯%homepath%\Documents\IISExpress\config\applicationHost.config才能解鎖。

<httpErrors lockAttributes="allowAbsolutePathsWhenDelegated,defaultPath">
 <!-- ... -->
</httpErrors>

引用自:https://stackoverflow.com/questions/18671975