Home > Blockchain >  How to access a value from appsettings.json in ASP.NET Core 6 controller
How to access a value from appsettings.json in ASP.NET Core 6 controller

Time:08-18

I have created a brand new ASP.NET Core Web API project 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.

CodePudding user response:

You will need to use .GetValue<type>, so try

Summary = _configuration.GetValue<string>("ProjectName");

You can also check detailed posts https://stackoverflow.com/a/58432834/3559462 (shows how to get value)

https://qawithexperts.com/article/asp-net/read-values-from-appsettingsjson-in-net-core/467 (Shows binding of Model from appsettings.json)

CodePudding user response:

These options maybe helpful:

  1. Maybe your appsettings.json file is not copied on the building. Right click on appsettings.json file and select properties. then Copy to Output Directory should be equal to Copy if newer or Copy always.
  2. If you have multiple appsettings like appsettings.json, appsettings.Development.json, appsettings.Production.json. Be sure your key(ProjectName) is in all of them
  • Related