2017-06-26 35 views
1

我知道如何在Web.config文件如何爲使用C#的IIS網站添加默認錯誤頁面?

<configuration> 
    <system.web> 
     <customErrors mode="RemoteOnly" defaultRedirect="mycustompage.htm"/> 
    </system.web> 
</configuration> 

使用asp.net添加錯誤頁IIS網站,我們可以在IIS中手動添加。

但我想添加基於網站名稱的錯誤頁面。

對於舉例..

網站名稱: 「Foo1」

錯誤頁面應該是:\ Foo1 \ err.html

如何從C#中使用控制檯添加錯誤頁面或WinForms。 請幫助我

+0

「使用控制檯或WinForms」是什麼意思?你想通過代碼來改變各個網站的web.config文件嗎? – Fabiano

+0

No @Fabiano ,.我想添加使用System.Web.Administation DLL的錯誤頁面。不是通過使用web.config – Prashee

回答

1

您可以在您的網站中修改您的web.config文件,假設它正在運行的應用程序池具有修改它的正確權限。

這可以使用WebConfigurationManager類來完成。

假設你只是想修改的defaultRedirect,你應該能夠使用如下代碼如下:

var configuration = WebConfigurationManager.OpenWebConfiguration("~"); 
var section = (CustomErrorsSection)configuration.GetSection("system.web/customErrors"); 
if(section != null) 
{ 
    section.DefaultRedirect = "yourpage.htm"; 
    configuration.Save(); 
} 

編輯:如果你是想通過Microsoft.Web.Administration要做到這一點,那麼下面的代碼應該允許您訪問特定網站的網頁配置,並將customErrors defaultRedirect設置爲新值:

using (ServerManager serverManager = new ServerManager()) 
{ 
    Configuration configuration = serverManager.GetWebConfiguration("your website name"); 

    ConfigurationSection customErrorsSection = configuration.GetSection("system.web/customErrors"); 
    customErrorsSection.SetAttributeValue("defaultRedirect", "/your error page.htm"); 
    serverManager.CommitChanges(); 
} 
+0

我們可以使用System.Web.Administration..like iisManager.Sites [「foo」]來編寫錯誤頁面,如下面的代碼片段:ErrorPage .... – Prashee

+0

@Prashee你想配置ASP customErrors,或IIS錯誤?此外,你是想從網站本身或其他應用程序做到這一點? – Thewads

+0

是的,從控制檯應用程序我想配置IIS錯誤來設置默認錯誤頁面。 – Prashee