65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 configSource 属性从 XML 文件管理 Web.config

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.95/5 (9投票s)

2007年10月10日

CPOL

1分钟阅读

viewsIcon

80894

如何使用 configSource 属性从 XML 文件管理 Web.config。

Screenshot - coolcode.gif

引言

configSource 属性首先在 .NET Framework 2.0 中引入,以支持外部配置文件。

在将我的网站上传到在线服务器后,我需要从 Web.Config 管理网站设置,因此我将 appSettingsconnectionStrings 以及我需要管理的所有设置保存在单独的 XML 文件中,以便于管理和组织。

这可以通过使用 configSource 属性来完成。configSource 属性首先在 .NET Framework 2.0 中引入,以支持外部配置文件。可以将此属性添加到任何配置节,以指定该节的外部文件。使用外部配置源在许多情况下都很有用。例如,如果您需要一种简单的方法来根据环境交换节的设置,可以将节放入外部 configSource 中。

使用代码

首先为每个 web.Config 节(如 appSettings.xmlConnectionString.xml 等)创建一个 XML 文件,并将其设置在 App_Data 文件夹中以进行保护。

将每个节从 web.config 复制并设置为 XML 文件,如下例所示 (appSettings.xml)

<?xml version="1.0" standalone="yes"?>
<appSettings>
  <add key="EnableErrorPage" value="false" />
  <add key="RequiredLogin" value="false" />
  <add key="PublicationsEmail" value="email@domain.com" />
  <add key="AdminFromEmail" value="email@domain.com " />
  <add key="AdminToEmail" value="email@domain.com " />
  <add key="SupportEmail" value="email@domain.com" />
</appSettings>

Web.config 中,将 appSettings 标签更改为

<appSettings configSource="App_Data\WebConfigXML\appSettings.xml"/>

configSource 属性必须是相对物理路径。

对每个 web.config 节(connectionStringssmtp 等)重复此操作。

现在,您可以使用 Gridview 控件从安全页面管理 XML 文件,以编辑和更新值。

结论

web.config 文件更小,因此更易于阅读,并且您不需要为每个环境提供完整的 web.config 文件。

© . All rights reserved.