2

I'm working on an ASP.NET Core Web App (MVC). I try to read a configuration value from my Web.config file using the following code.

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

My Web.config file looks like the following:

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

The output in the debugger shows the following:

enter image description here

Unfortunately, no value is returned. What am I doing wrong?

Thanks a lot in advance!

marcs
  • 73
  • 7
  • Pls see to https://stackoverflow.com/questions/46996480/how-to-read-web-config-file-in-net-core-app – Mansur Kurtov Jul 07 '21 at 12:16
  • Try using var myconfig = ConfigurationManager.AppSettings["myConfig"].Value; – Priyanka Jul 07 '21 at 12:17
  • 1
    FYI, .net core uses appsettings.json for file instead of web.config. Please check here https://stackoverflow.com/a/62413846/6060754 – Srusti Thakkar Jul 07 '21 at 12:22
  • @SrustiThakkar - Thanks a lot! This is working for me. But how can I distinguish from which appsettings.json the values should be read? In development, it should read from appsettings.Development.json and in production from appsettings.json. – marcs Jul 07 '21 at 12:44
  • 1
    Yes, You can configure that in launchsetting file. Please read more about this int this blog https://www.c-sharpcorner.com/article/app-settings-file-according-to-environment-variable-dotnet-core-api/ – Srusti Thakkar Jul 07 '21 at 13:10

1 Answers1

1

The .Net Core application settings are stored in Json (appsettings.json) format by default, and the configuration process is read:

1.I wrote these parameters in appsettings.json.

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

2.And take the values as follows:

            //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");
Tupac
  • 2,590
  • 2
  • 6
  • 19