I have created a brand new ASP.NET Core Web API project (.NET 6) from the default template provided in Visual Studio 2022. After that I added a config key in the appsettings.json file and am trying to access it inside the controller
class, but can't.
My appsettings.json file is below:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ProjectName" : "VeryFunny"
}
The controller code is below:
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly IConfiguration _configuration;
public WeatherForecastController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpGet(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = _configuration["ProjectName"] // <-- I added this
})
.ToArray();
}
}
I receive null
instead of VeryFunny
string in the above method, where I have added an arrow comment. I assumed that after the merging of Startup.cs
class and Program.cs
class in .NET 6, IConfiguration
is easily available now, but it seems I was wrong.
UPDATE:
This is a bare bone project you get when you create a new ASP.NET Core Web API targeting .NET 6, in Visual Studio 2022. When I create a new project targeting .NET 5, I have no issues because in that Startup.cs
and Program.cs
are separate classes and an instance of IConfiguration
is already injected in Startup
class, whereas this is not the case in .NET 6. There is an existing SO question which asks the same question, but that question and its answers are focused on .NET implementations prior to .NET 6, for example .NET Core 2.x, .NET 5 etc. Mine is .NET 6 specific.
AppSettings
parent element; whilst yourProjectName
sits on the root... By convention you'd want to nest it underAppSettings
, though it is possible to access it programmatically without that.