我正在研究 ASP.NET MVC 项目并决定将一些功能提取到一个单独的类库项目中(在同一个解决方案中)。
我移动了 <appSettings></appSettings>
中的一些元素来自 Web.config
在主项目中(我们称之为项目 A)到 App.config
在类库项目中(我们称之为项目 B)。我添加了对 System.Configuration.dll 的引用以访问项目 B 中的 ConfigurationManager。
下面是项目 B 的示例 App.config 文件。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Key1" value="Value1"/>
<add key="Key2" value="Value2"/>
</appSettings>
</configuration>
我按如下方式访问这些设置(在项目 B 中)。
string key1 = ConfigurationManager.AppSettings["Key1"];
string key2 = ConfigurationManager.AppSettings["Key2"];
我注意到
key1
的值和 key2
返回者 ConfigurationManager
是 null
.调试时我看到
ConfigurationManager
从原始值中提取值 Web.config
在项目 A 中(在 <appsettings></appsettings>
部分我没有移动到项目 B 中的其他内容)!这对我来说没有任何意义。有人能告诉我我做错了什么,以便我可以访问 App.config 中的设置吗?
谢谢。
最佳答案
App.config
驻留在类库项目中的那些不会被加载(至少不是没有额外的努力),框架加载的唯一配置是 客户配置(即引用和使用您的类库的项目的 Web.config
)。
见 this answer对于可能的解决方案。
关于asp.net-mvc - ConfigurationManager 读取错误的文件 - Web.config 而不是 App.config,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18703422/