I created a simple ASP.NET Core 6 MVC application in which I am just reading values from the appsettings.json
file.
In my appsettings
, I created two sections SectionA
and SectionB
:
{
"SectionA": {
"SectionASubItem1": "test value",
"SectionASubItem2": "test value2"
},
"SectionB": {
"SectionBSubItem1": "test value",
"SectionBSubItem2": "test value2"
}
}
I also created a class to map this value with class properties:
This is what my MyConfiguration
class looks like:
public class MyConfiguration
{
public SectionA SectionA { get; set; }
public SectionB SectionB { get; set; }
}
public class SectionA
{
public string SectionASubItem1 { get; set; }
public string SectionASubItem2 { get; set; }
}
public class SectionB
{
public string SectionBSubItem1 { get; set; }
public string SectionBSubItem2 { get; set; }
}
In the program.cs
class I created a variable type of IConfigurationRoot
in which I am storing the JSON file properties:
var myConfiguration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
and mapping the section like this:
builder.Services.Configure<SectionA>(myConfiguration.GetSection("SectionA"));
builder.Services.Configure<SectionB>(myConfiguration.GetSection("SectionB"));
The problem is when I am reading the sectionA
and sectionB
inside the controller I am getting null. Due to this, I am not getting values from JSON file.
public readonly MyConfiguration configuration;
public WeatherForecastController()
{
configuration = new MyConfiguration();
}
[HttpGet(Name = "GetWeatherForecast")]
public IActionResult Get()
{
// Here I am getting null
var sectionA = configuration.SectionA;
if (sectionA == null)
return BadRequest();
return Ok();
}