8

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.

6
  • There's useful info on this here: stackoverflow.com/a/67292524/361842 - note: in this case they'd put custom attributes under an AppSettings parent element; whilst your ProjectName sits on the root... By convention you'd want to nest it under AppSettings, though it is possible to access it programmatically without that.
    – JohnLBevan
    Commented Aug 18, 2022 at 11:21
  • Please check out the docs.
    – Guru Stron
    Commented Aug 18, 2022 at 11:43
  • 1
    Does this answer your question? Getting value from appsettings.json in .net core
    – Manish
    Commented Aug 18, 2022 at 11:50
  • @Manish No. I updated my question to be more specific.
    – user419022
    Commented Aug 18, 2022 at 23:43
  • Have you modified codes in Program.cs?I tried with your codes ,it works well in .net 6 Commented Aug 19, 2022 at 2:14

3 Answers 3

13

I figured out how to access appsettings.json from controller using IConfiguration interface inside the constructor.

below my example of code:

public class HomeController : Controller
{

        private readonly IConfiguration _config;
        private string ConnectionString;

        public HomeController(IConfiguration configuration)
        {
            _config = configuration;
            ConnectionString = _config["Configurations:ConnectionString"];
            Console.WriteLine(ConnectionString);
        }

The connection String (in this case was the parameter inside json file) showed successfully! my appsettings.json code:

"Configurations": {
    "ConnectionString": "MyDBConnectionStringExample;"
  }

I really recommend that you will need a separated class to handle all the database communication if it's the case, otherwise it work's well... hope it helps someone.

2
  • This was a fantastic answer. Just what I needed. Thanks for writing this one up. Could not figure out how to get config value in my controller.
    – raddevus
    Commented Aug 14, 2023 at 22:58
  • 1
    Thank you very much for leaving your feedback, I'm glad I could help. @raddevus Commented Aug 24, 2023 at 16:21
8

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)

Update:

I created new .NET Core 6 API project and used this code

  private readonly IConfiguration _configuration;
    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuratio)
    {
        _logger = logger;
        _configuration = configuratio;
    }

    [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.GetValue<string>("ProjectName")

    })
        .ToArray();

It worked for me, here is the GIF image

enter image description here

2
  • It didn't help. I updated my question to be more specific.
    – user419022
    Commented Aug 18, 2022 at 23:47
  • @user419022 Updated my answer, I tried creating new .NET Core 6 project in VS 2022 and tested output, looks ok to me. Commented Aug 19, 2022 at 8:16
0

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
1
  • Nops, It didn't help. I updated my question to be more specific.
    – user419022
    Commented Aug 18, 2022 at 23:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.