Not sure what am I missing here but I am not able to get the values from my appsettings.json in my .net core application. I have my appsettings.json as:
{
"AppSettings": {
"Version": "One"
}
}
Startup:
public class Startup
{
private IConfigurationRoot _configuration;
public Startup(IHostingEnvironment env)
{
_configuration = new ConfigurationBuilder()
}
public void ConfigureServices(IServiceCollection services)
{
//Here I setup to read appsettings
services.Configure<AppSettings>(_configuration.GetSection("AppSettings"));
}
}
Model:
public class AppSettings
{
public string Version{ get; set; }
}
Controller:
public class HomeController : Controller
{
private readonly AppSettings _mySettings;
public HomeController(IOptions<AppSettings> settings)
{
//This is always null
_mySettings = settings.Value;
}
}
_mySettings
is always null. Is there something that I am missing here?
Best Answer
Program and Startup class
.NET Core 2.x
You don't need to new
IConfiguration
in theStartup
constructor. Its implementation will be injected by the DI system..NET Core 1.x
You need to tell
Startup
to load the appsettings files.Getting Values
There are many ways you can get the value you configure from the app settings:
ConfigurationBuilder.GetValue<T>
Let's say your
appsettings.json
looks like this:Simple Way
You can inject the whole configuration into the constructor of your controller/class (via
IConfiguration
) and get the value you want with a specified key:Options Pattern
The
ConfigurationBuilder.GetValue<T>
works great if you only need one or two values from the app settings. But if you want to get multiple values from the app settings, or you don't want to hard code those key strings in multiple places, it might be easier to use Options Pattern. The options pattern uses classes to represent the hierarchy/structure.To use options pattern:
IOptions<T>
into the constructor of the controller/class you want to get values on1. Define configuration classes to represent the structure
You can define classes with properties that need to exactly match the keys in your app settings. The name of the class does't have to match the name of the section in the app settings:
2. Register the configuration instance
And then you need to register this configuration instance in
ConfigureServices()
in the start up:3. Inject IOptions
Lastly on the controller/class you want to get the values, you need to inject
IOptions<AppIdentitySettings>
through constructor: