Reputation: 73
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:
Unfortunately, no value is returned. What am I doing wrong?
Thanks a lot in advance!
Upvotes: 2
Views: 849
Reputation: 2932
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");
Upvotes: 1