In ASP.NET Core application configuration settings like the database connection strings or some key value can come from the following different configurations sources.
- Files (appsettings.json, appsettings.{Environment}.json, where {Environment} is the app's current hosting environment)
- User secrets
- Environment variables
- Command-line arguments
ASP.NET Core IConfiguration service
- IConfiguration service is setup to read configuration information from all the various configuration sources in asp.net core
- If you have a configuration setting with the same key in multiple configuration sources, the later configuration sources override the earlier configuration sources
- CreateDefaultBuilder() method of the WebHost class which is automatically invoked when the application starts, reads the configuration sources in a specific order.
- Following is the default order in which the various configuration sources are read
- appsettings.json
- appsettings.{Environment}.json
- User secrets
- Environment variables
- Command-line arguments
EXAMPLE
appsettings.json file: In this file we can add itme as key value pair
{
"AllowedHosts": "*",
"MyKeyValue": "Value of MyKey from appsettings.json"
}
Accessing configuration information
To access configuration information in the Startup class, inject the IConfiguration service provided by the Framework.
To access configuration information in the Startup class, inject the IConfiguration service provided by the Framework.
public class Startup
{
private IConfiguration _configuration;
// Notice we are using Dependency Injection here
public Startup(IConfiguration configuration)
{
_configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
await context.Response.WriteAsync(_configuration["MyKeyValue"]);
});
}
}
Comments
Post a Comment