The entire configuration approach in .NET Core is really flexible, but not at all obvious in the beginning. This is probably easiest to explain with an example:
Suppose the appsettings.json file looks like this:
{ "option1": "value1_from_json", "ConnectionStrings": { "DefaultConnection": "Server=,\\SQL2016DEV;Database=DBName;Trusted_Connection=True" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } } }
To get data from the appsettings.json file, you first need to configure ConfigurationBuilder in Startup.cs as follows:
public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true); if (env.IsDevelopment()) {
You can then access the configuration directly, but itβs better to create Options classes to store this data, which you can then embed in your controller or other classes. Each of these parameter classes represents a separate section of the appsettings.json file.
In this code, connection strings are loaded into the ConnectionStringSettings class and another option is loaded into the MyOptions class. The .GetSection method gets a specific part of the appsettings.json file. Again, this is in Startup.cs:
public void ConfigureServices(IServiceCollection services) { ... other code
These are the classes into which the configuration data is loaded. Notice how the property names combine with the settings in the json file:
public class MyOptions { public string Option1 { get; set; } } public class ConnectionStringSettings { public string DefaultConnection { get; set; } }
Finally, you can access these settings by inserting OptionsAccessor into the controller as follows:
private readonly MyOptions _myOptions; public HomeController(IOptions<MyOptions > optionsAccessor) { _myOptions = optionsAccessor.Value; var valueOfOpt1 = _myOptions.Option1; }
As a rule, the whole configuration process in Core is quite different. Thomas Ardal has a good explanation of this on his website here: http://thomasardal.com/appsettings-in-asp-net-core/
There is also a more detailed explanation of the configuration in ASP.NET Core in the Microsoft documentation .
NB: All of this has changed a bit in Core 2, I need to get back to the answer above, but at the same time, this Coding Blast post by Ibrahim Shut is a great introduction with many examples.
NB No. 2: There are a number of configuration errors that are easy to make using the above. Look at this answer if it does not work for you.