ASP.NET Core has a lot of configuration options out of the box. One of the added possibilities is to store your configuration settings inside a JSON document.
Nice advantage of using a JSON document is that you can logically group the related configuration settings in separate sections inside your document:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"Logging": { | |
"IncludeScopes": false, | |
"LogLevel": { | |
"Default": "Debug", | |
"System": "Information", | |
"Microsoft": "Information" | |
} | |
} | |
"Data":{ | |
"ConnectionString":"<connection info>" | |
} | |
} |
To read values from a subsection, you specify the subsection name and the property name separated by a colon:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Startup | |
{ | |
public Startup(IHostingEnvironment env) | |
{ | |
var builder = new ConfigurationBuilder() | |
.SetBasePath(env.ContentRootPath) | |
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) | |
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true) | |
.AddEnvironmentVariables(); | |
Configuration = builder.Build(); | |
} | |
public IConfigurationRoot Configuration { get; } | |
// This method gets called by the runtime. Use this method to add services to the container. | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
var connectionString=Configuration["Data:ConnectionString"]; | |
} | |
/*Removed other code*/ | |
} |