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

标签 asp.net-mvc configurationmanager

我正在研究 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返回者 ConfigurationManagernull .

调试时我看到 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/

相关文章:

asp.net-mvc - MVC Controller - Http Post 映射值

c# - 无法在 .NET 项目中使用 PerUserRoaming 参数保存配置文件

ASP.NET Web.Config ConfigurationManager.AppSettings 文件缓存

c# - 如何获取 ConfigurationSection 属性作为 System.Type

asp.net-mvc - Entity Framework /Glimpse 持续时间差异

使用 iPhone UIWebView 时的 Asp.Net 表单例份验证

c# - 如何使用 Javascript 单击按钮时触发 HTML 帮助程序

c# - 无法从 Microsoft.AspNet.Identity 检索 UserId

c# - 在运行时更改 App.config

.net - 如何从命令行参数中选择 .Net 应用程序配置文件?