Asp .Net Configuration


In this article I will give some tips on how one can work with configuration with ASP .Net apps. Almost all or any ASP .Net app anyway have this Microsoft.Extensions.Configuration.IConfiguration
or simply put it as type IConfiguration
.
There are usually one or two json
files appsettings.json
or or and the appsettings.Development.json
. These contain settings for the app to use depending on the type of environment the instance is being run on. The first is for production and the later for development environment and more can de added as well.
Now let's say or appsettings.json
is like below. Most of these config have provision for logging settings. say in production, the default might be Information
meaning anything below that like Debug or Trace might not be logged. For development, the default might be Debug
meaning almost all except might be Trace
may not be logged which deserves another article for sure.
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" ... ... } }, "SomeApp": { "Host": "192.168.a.l", "Email": "abc@comp.co", "Location": { "First": "Gatsby" } }
}}
In case we need to retrieve the Host address of our SomeApp, then in the class which is loaded by the ASP .Net server let's say FirstService
class, the IConfiguration
can be dependency injected and the app's settings retrieved like below.
public class FirstService { public readonly IConfiguration _configuration;
public FirstService(IConfiguration configuration)
{ _configuration = configuration
}
public void RunApp()
{
Console.WriteLine("Host Config - " + _configuration["SomeApp:Host"]);
}
}
The _configuration["SomeApp:Host"]
should give the address value which is "192.168.a.l", in this case.
The _configuration["SomeApp:Host:Location:First"]
should give the location value and so on.
Similarly additional configurations as json files can be added to be loaded in the Startup
or the Program
class as well. The fetching mechanism need not be a string key, it can be
_configuration.Get() to bind the configuration to type P
and be retrieved in a more strict type way as well.