【问题标题】:ConfigurationManager.AppSettings returns nothingConfigurationManager.AppSettings 不返回任何内容
【发布时间】:2021-09-17 23:34:47
【问题描述】:

我正在开发一个 ASP.NET Core Web 应用程序 (MVC)。我尝试使用以下代码从我的 Web.config 文件中读取配置值。

var myConfig = ConfigurationManager.AppSettings["myConfig"];

我的 Web.config 文件如下所示:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <compilation debug="true"  />
        <httpRuntime  />
    </system.web>
    <appSettings>
        <add key="myConfig" value="12345" />
    </appSettings>
</configuration>

调试器中的输出显示如下:

很遗憾,没有返回任何值。我做错了什么?

提前非常感谢!

【问题讨论】:

  • 尝试使用 var myconfig = ConfigurationManager.AppSettings["myConfig"].Value;
  • 仅供参考,.net 核心使用 appsettings.json 作为文件而不是 web.config。请在此处查看stackoverflow.com/a/62413846/6060754
  • @SrustiThakkar - 非常感谢!这对我有用。但是我如何区分应该读取哪个 appsettings.json 值?在开发中,它应该从 appsettings.Development.json 中读取,在生产中应该从 appsettings.json 中读取。
  • 是的,您可以在启动设置文件中进行配置。请在此博客c-sharpcorner.com/article/… 阅读有关此内容的更多信息

标签: c# asp.net-mvc asp.net-core web-config configurationmanager


【解决方案1】:

.Net Core应用设置默认以Json(appsettings.json)格式存储,读取配置过程:

1.我在appsettings.json中写了这些参数。

"name": "wen",
    "age": 26,
    "family": {
      "mother": {
        "name": "Test",
        "age": 55
      },
      "father": {
        "name": "Demo",
        "age": 56
      }
    },

2.取值如下:

            //Add json file path
    var builder = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json");
      
        //Create configuration root object
            var configurationRoot = builder.Build();

            //Take the name part under the configuration root
            var nameSection = configurationRoot.GetSection("name");
            //Take the family part under the configuration root
            var familySection = configurationRoot.GetSection("family");
            //Take the name part under the mother part under the family part
            var motherNameSection = familySection.GetSection("mother").GetSection("name");
            //Take the age part under the father part under the family part
            var fatherAgeSection = familySection.GetSection("father").GetSection("age");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-27
    • 2019-04-06
    • 2012-02-15
    • 2020-09-07
    • 2021-11-22
    • 2015-11-06
    • 2013-11-14
    • 2014-03-23
    相关资源
    最近更新 更多