ConfigurationManager读取错误的文件 - Web.config而不是App.config

[英]ConfigurationManager reading wrong file - Web.config instead of App.config


I was working on ASP.NET MVC project and decided to extract some functionality to a separate class library project (in the same solution).

我正在研究ASP.NET MVC项目,并决定将一些功能提取到一个单独的类库项目(在同一个解决方案中)。

I moved some of the elements in <appSettings></appSettings> from Web.config in main project (let's call it project A) to App.config in class library project (let's call it project B). I added a reference to System.Configuration.dll to access the ConfigurationManager in project B.

我将 中的一些元素从主项目中的Web.config(让我们称之为项目A)移动到类库项目中的App.config(让我们称之为项目B)。我添加了对System.Configuration.dll的引用以访问项目B中的ConfigurationManager。

Sample App.config file is for project B is below.

示例App.config文件用于项目B,如下所示。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="Key1" value="Value1"/>
    <add key="Key2" value="Value2"/>
  </appSettings>
</configuration>

I access these settings as follows (in project B).

我按如下方式访问这些设置(在项目B中)。

string key1 = ConfigurationManager.AppSettings["Key1"];
string key2 = ConfigurationManager.AppSettings["Key2"];

I noticed that the values for key1 and key2 returned by ConfigurationManager are null.

我注意到ConfigurationManager返回的key1和key2的值为null。

When debugging I see that ConfigurationManager pull values from the original Web.config in project A (the other entires in <appsettings></appsettings> section that I did not move to project B)!

在调试时,我看到ConfigurationManager从项目A中的原始Web.config中拉出值(另一个在 部分中,我没有移动到项目B)!

This does not make any sense to me. Could someone tell me what I am doing wrong, so I could access settings in App.config?

这对我没有任何意义。有人能告诉我我做错了什么,所以我可以访问App.config中的设置吗?

Thanks.

谢谢。

1 个解决方案

#1


7  

App.config that resides in a Class Library project would not be loaded (at least not without extra effort), the only configuration loaded by the framework is the Client configuration (i.e the Web.config of a project that references and uses your Class Library).

不会加载驻留在类库项目中的App.config(至少不需要额外的努力),框架加载的唯一配置是客户端配置(即引用和使用类库的项目的Web.config) )。

See this answer for possible solutions.

请参阅此答案以了解可能的解


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2013/09/09/44f0f424310415121a81e0dae4855186.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号