务实地使用C#添加IIS网站的默认错误页面



我知道如何使用web.config文件中的asp.net添加IIS网站的错误页面

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

我们可以在IIS中手动添加。

但我想根据网站名称添加错误页面。

例如..

网站名称:&quot" foo1"

错误页面应为: foo1 err.html

如何使用控制台或Winforms从C#添加错误页面。请帮助我

您可以在网站中修改您的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进行此操作,则以下代码应允许您访问特定网站的Web配置,并将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();
}

最新更新