3 回答

TA貢獻1780條經(jīng)驗 獲得超4個贊
* 2016年4月更新
當(dāng).net代碼拋出異常(404,403,500等)時使用customErrors屬性,并且當(dāng)IIS本身拋出異常時使用httpErrors屬性。
/ myfakeextensionslessurl - > httpErrors 404
/myfakeaspsx.aspx - > customErrors 404
/myfakeimage.jpg - > httpErrors 404
/throw500.apx - > customErrors 500
/ throw500 - > customErrors 500
試圖正確配置這一點有很多陷阱。因此,如果您正在尋找一個快速示例,您擁有的最佳選擇是:
示例1:使用html頁面
<system.web> <customErrors mode="RemoteOnly" defaultRedirect="/Error500.html" redirectMode="ResponseRewrite"> <error statusCode="403" redirect="/Error403.html" /> <error statusCode="404" redirect="/Error404.html" /> <error statusCode="500" redirect="/Error500.html" /> </customErrors></system.web><system.webServer> <httpErrors errorMode="DetailedLocalOnly" existingResponse="Auto"> <remove statusCode="403" /> <remove statusCode="404" /> <remove statusCode="500" /> <error statusCode="403" responseMode="File" path="Error403.html" /> <error statusCode="404" responseMode="File" path="Error404.html" /> <error statusCode="500" responseMode="File" path="Error500.html" /> </httpErrors></system.webServer>
示例2:使用aspx頁面
<system.web> <customErrors mode="RemoteOnly" defaultRedirect="/Error500.html" redirectMode="ResponseRewrite"> <error statusCode="403" redirect="/Error403.aspx" /> <error statusCode="404" redirect="/Error404.aspx" /> <error statusCode="500" redirect="/Error500.aspx" /> </customErrors></system.web><system.webServer> <httpErrors errorMode="DetailedLocalOnly" existingResponse="Auto"> <remove statusCode="403" /> <remove statusCode="404" /> <remove statusCode="500" /> <error statusCode="403" responseMode="ExecuteURL" path="Error403.aspx" /> <error statusCode="404" responseMode="ExecuteURL" path="Error404.aspx" /> <error statusCode="500" responseMode="ExecuteURL" path="Error500.aspx" /> </httpErrors></system.webServer>
在aspx錯誤頁面中,您需要執(zhí)行以下操作(示例404頁面):
<% Response.StatusCode = 404; Response.TrySkipIisCustomErrors = true; %>
注意:無法在customErrors部分中使用擴展名更少的URL !。(沒有黑客)
一種解決方法是禁用自定義錯誤,讓http錯誤處理自定義頁面。朋友創(chuàng)建了這樣的設(shè)置,當(dāng)我找到一些時間時,我會分享代碼。
背景
一個好的自定義錯誤頁面將:
在本地訪問問題頁面時顯示真實的異常
遠程訪問問題頁面時顯示自定義頁面
不會重定向,而只是顯示錯誤頁面內(nèi)容(因為seo原因)
將顯示正確的狀態(tài)代碼
所以要澄清我們的配置中的一些選項:
<customErrors mode="RemoteOnly"
。您可以指定在這里:On
,Off
,RemoteOnly
。On
=始終顯示自定義錯誤頁面Off
=始終顯示真實的錯誤RemoteOnly
=在本地顯示錯誤,但遠程顯示自定義錯誤頁面。所以我們想要RemoteOnly
聲明1<customErrors redirectMode="ResponseRewrite"
。你可以在這里指定:ResponseRedirect
或ResponseRewrite
。該ResponseRedirect
模式將錯誤頁面重定向到自定義錯誤頁面。對于鏈接爬蟲(SEO),這將導(dǎo)致302 - > 500,但您希望鏈接爬蟲獲得500錯誤。<httpErrors errorMode="DetailedLocalOnly"
。這相當(dāng)于customErrors
模式。選擇您有:Custom
,Detailed
,DetailedLocalOnly
。
一篇很有幫助我的博客文章是:http://benfoster.io/blog/aspnet-mvc-custom-error-pages
添加回答
舉報