dav*_*ooh 2 .net c# asp.net web-config
我正在开发一个 ASP.NET 项目,我需要在我的网络应用程序的 appSettings 部分添加一些设置。
现在这些设置越来越多,所以我想将它们组织在不同的文件中。我在应用程序的不同目录中创建了其他 web.config 文件,添加如下内容:
<?xml version="1.0"?>
<configuration>
<system.web>
</system.web>
<appSettings>
<add key="settingKey" value="settingValue" />
</appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)
但是当我尝试通过访问它们时ConfigurationManager.AppSettings["settingKey"],我得到了null。
那么,是否可以将设置拆分到不同的文件中?是否有另一种方法可以逻辑地组织应用程序设置值?
我知道这太旧了,可能甚至不适用于 .NET Core,但对于那些来自 Google 并使用非 .NET Core json 配置文件的人来说。这就是我通常做的...
我习惯configSources将所有配置设置从web.config. 这允许您通过提供相对位置将特定的配置节指向不同的文件,例如以下是configSource在配置节(在根web.config文件中)中声明 a 的方式...
<configuration>
<log4net configSource="Config\debug\log4net.config" />
<appSettings configSource="config\debug\settings.config" />
<connectionStrings configSource="config\debug\connections.config" />
...
</configuration>
Run Code Online (Sandbox Code Playgroud)
您可以根据需要命名这些文件,只需确保指定的路径和文件存在于解决方案中即可。这是 settings.config 文件的样子......
<?xml version="1.0"?>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="foo" value="bar" />
</appSettings>
Run Code Online (Sandbox Code Playgroud)
现在,相对路径是相对于项目根目录的......
在上图中,您可以看到我为不同的部署环境提供了两种不同的路径,这是因为显然我的连接字符串和设置在生产中是不同的。
然后您可以使用配置转换,以便应用程序无论处于调试模式还是发布模式都可以使用正确的配置文件...
这就是Web.Debug.config文件的样子......
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<log4net configSource="Config\debug\log4net.config" xdt:Transform="Replace" />
<appSettings configSource="config\debug\settings.config" xdt:Transform="Replace" />
<connectionStrings configSource="config\debug\connections.config" xdt:Transform="Replace" />
</configuration>
Run Code Online (Sandbox Code Playgroud)
发布版本几乎相同...替换提供给 configSource 属性的路径。仅此而已。还有其他支持 configSource 设置的 web.config 元素,例如许多system.serviceModel子元素。
| 归档时间: |
|
| 查看次数: |
3320 次 |
| 最近记录: |