為什麼在這種情況下在 web.config 中設置 customErrors 不起作用?
在我在共享主機提供商中發布的 ASP.NET 3.5 網站中,我已經像這樣配置了我的 web.config 文件:
<customErrors mode="On" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="AccessDenied.htm"/> <error statusCode="404" redirect="FileNotFound.htm"/> </customErrors>如果使用者請求的頁面不存在(例如“www.example.com/NotExistPage.aspx”),使用者將被重定向到我們預期的 FileNotFound.htm 頁面。
但是,如果使用者請求一些地址,例如:“www.example.com/NotExistDirectory”,而沒有 .aspx 副檔名,使用者將遇到 IIS 7.5 錯誤頁面:
HTTP 錯誤 404.0 - 未找到 您要查找的資源已被刪除、名稱已更改或暫時不可用。
詳細錯誤資訊:
Module IIS Web Core Notification MapRequestHandler Handler StaticFile Error Code 0x80070002 Requested URL http://www.example.com:80/NotExistDirectory Physical Path D:\Websites\example\example.com\wwwroot\NotExistDirectory Logon Method Anonymous Logon User Anonymous這是一個不友好的黃頁,我們沒想到。
我想知道在 webconfig 中設置 customeError 是否不支持這種類型的地址?我怎樣才能防止使用者看到這個黃頁。
編輯: 感謝大衛的回答,但我找到了實際原因和正確的解決方案。請看我的回答。
@Mostafa:我遇到了完全相同的問題。我發現可以通過將以下內容添加到 web.config 文件來解決它:
<system.webServer> <httpErrors errorMode="Custom"> <remove statusCode="404" subStatusCode="-1" /> <error statusCode="404" subStatusCode="-1" prefixLanguageFilePath="" path="/MyErrorPage.aspx" responseMode="ExecuteURL" /> </httpErrors> </system.webServer>
這很有趣,幾年後我突然發現問題出在哪裡。
感謝@David的解決方案,但原因和完整的解決方案如下:
通過將
customErrors模式設置為“On”,僅當我們在 ASP.NET 應用程序中遇到異常時才有效,而當我們嘗試訪問nonExistingdirectoryOrnotExsitingStaticResouce時,IIS 會呈現 404 錯誤並且它不會到達 asp.net 執行時並由 IIS 直接提供服務。所以我們需要在 Web.config 中為 IIS 添加如下配置:
<system.webServer> <httpErrors errorMode="Custom"> <remove statusCode="404"/> <error statusCode="404" path="~/404.html" responseMode="File" /> </httpErrors> <system.webServer>設置
responseMode為“File”很重要,否則狀態碼會自動從 404 更改為 200 。所以從客戶端的角度來看,他們沒有得到實際的 404 狀態碼。