1

I have an asp.net core 2 webapi service. I want to read appsettings.json but I cannot figure it out. As usual, when I search the internet I get a dozen completely different answers based on various versions of the framework that ultimately don't seem to work.

As an example appsettings.json:

"AppSettings": {
  "Domain": "http://localhost"
}

Firstly I tried this:

Added via nuget Microsoft.Extensions.Configuration and Microsoft.Extensions.Configuration.Json

In my ConfigureServices method I added:

services.AddSingleton<IConfiguration>(Configuration);

In my Controller I injected the config:

IConfiguration iconfig;
public ValuesController(IConfiguration iConfig)
{
    iconfig = iConfig;
}

To retrieve it:

return "value: " + iconfig.GetValue<string>("AppSettings:Domain");

I can see the controller constructor being called and passing in a config, but the value is always null.

I did notice that Startup already passes in an IConfiguration. Is it a case of yet another change in implementation and i need to do something different?

[edit] I've now read https://joonasw.net/view/aspnet-core-2-configuration-changes

Which says it's all change again and it's auto injected, but after following the code it doesn't actually say how you get your hands on the data in your controller.

Neil Walker
  • 6,400
  • 14
  • 57
  • 86
  • Inject `IConfigurationRoot` into your controller and then access your value like this: `config["AppSettings:Domain"]` – peinearydevelopment Nov 14 '17 at 20:13
  • The code you posted works fine for me. I only had to fix the _appsettings.json_ because what you posted is not a valid json. – anserk Nov 14 '17 at 21:28

1 Answers1

1

You can take a look at my answer here: https://stackoverflow.com/a/46940811/2410655

Basically you create a class that matches the properties you define in appsettings.json file (In the answer it's the AppSettings class).

And then in ConfigureServices(), you inject that class using services.Configure<>. That class will be available in all Controllers by DI.

To access its data, you can take a look at @aman's original question post from the link above.

public class HomeController : Controller
{
    private readonly AppSettings _mySettings;

    public HomeController(IOptions<AppSettings> appSettingsAccessor)
    {
        _mySettings = appSettingsAccessor.Value;
    }
}
David Liang
  • 20,385
  • 6
  • 44
  • 70