2010-08-18 29 views
21

我們通常在Global.asax中捕獲未處理的異常,然後我們重定向到一個友好的友好錯誤頁面。這對於Live環境很好,但在我們的開發環境中,我們希望檢查CustomErrors是否關閉,如果是,請拋出醜陋的錯誤。有沒有辦法以編程方式檢查ASP.NET應用程序的CustomErrors是否設置爲Off?

是否有一種簡單的方法來檢查CustomErrors是否通過代碼關閉?

+0

的可能重複的[檢查的customErrors在代碼接通(http://stackoverflow.com/questions/1367640/checking-customerrors-turned-on-in-code) – Naz 2014-03-01 10:23:03

回答

12

沒錯,通WebConfigurationManager

System.Configuration.Configuration configuration = 
    System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/"); 

System.Web.Configuration.CustomErrorsSection section = 
    (CustomErrorsSection)configuration.GetSection("system.web/customErrors"); 

一旦你的部分,你可以檢查模式是否開啓或關閉如下:

CustomErrorsMode mode = section.Mode; 
if (mode == CustomErrorsMode.Off) 
{ 
    // Do something 
} 
1

這應該做的伎倆..

using System.Web.Configuration; 
using System.Configuration; 

// pass application virtual directory name 
Configuration configuration = WebConfigurationManager.OpenWebConfiguration("/TestWebsite"); 
CustomErrorsSection section = (CustomErrorsSection)configuration.GetSection("system.web/customErrors"); 
CustomErrorsMode mode=section.Mode; 
32

我建議使用以下屬性:

HttpContext.Current.IsCustomErrorEnabled 

如前所述here,IsCustomErrorEnabled需要更多像僅限遠程的東西考慮:

的IsCustomErrorEnabled酒店結合三個值來告訴你 是否自定義錯誤是針對特殊需求的功能。這不是 就像讀取web.config文件以檢查 部分一樣簡單。在幕後有更多的事情可以確定是否啓用自定義錯誤 。

酒店着眼於這三個值:

  1. 的Web.config的<部署>部分的零售物業。這是一個 有用的屬性,用於在將應用程序部署到生產 服務器時進行設置。這會覆蓋任何其他自定義錯誤的設置。

  2. web.config的< customErrors>部分的mode屬性。此設置 指示是否啓用定製錯誤,如果是,是否 僅對遠程請求啓用。

  3. HttpRequest對象的IsLocal屬性。如果自定義錯誤僅針對遠程 請求啓用,則需要知道請求是否來自遠程 計算機。

+4

這應該被接受的回答。 – 2016-07-20 17:42:40

相關問題