Configuration Values in ASP.NET Core
Create ASP>NET Core Project
Add Parameters on appsettings.json
We have added setting section named ApplicationParameters & have added four parameters under it i.e. SQLServerConnection, EmailServer, ServiceURL & MaxLimitUsers
Add properties class
We will add properties class which corresponds to the settings specified in appsettings.json ApplicationParameters section.
Bind configuration to your class in Startup class
Let’s add service in startup class to read configuration values into an instance of properties class ApplicationParameters.
The default order in which values are read from JSON file is
- appsettings.json
- appsettings.{environment}.json
If same key exists in both appsettings.json & appsettings.{environment}.json then on runtime it should display the value from appsettings.{environment}.json
Add a controller to read parameters using IOptions
The sample controller has been added to inject configuration in constructor injection using IOptions & IOptionsSnapshot interfaces. It has one action index which return values of configuration parameters read using IOptions & IoptionsSnapshot
Run & Test the code
When we run the code and navigate to path api/AppParamters/Index then configuration values are displayed for IOption & IOptionsSnapshot. Both values match as it has been read when the app started.
Now without stopping application modify values in appsettings.json to new values & save changes
Now refresh browser (without restarting application) and check values for both IOptions & IOptionsSnapshot. You will see that only IOptionsSnapshot contains the latest modified values as it is designed to read values before each request
IOptionsMonitor also works in a way similar to IOptionsSnapshot only difference being in the IOptionMonitor service lifetime is Singleton instead of Scoped as in IOptionsSnapshot.
Guidelines for storing configuration values
- All sensitive data like passwords, personal information should never be stored in plain text in configuration i.e. if at all it is being stored in configuration then it should be encrypted
- As far as possible production secrets should be different from development & staging secrets.
- Use different naming conventions for configuration files on different environments like appsettings.development.json and appsettings.production.json.
Summary
We saw how to read configuration values in ASP.NET Core using IOtions Pattern. We can inject IOption into service, controller, etc using constructor injection.
There are 3 types of IOptions interface IOptions, IOptionsSnapshot & IOptionsMonitor. IOptionsSnapshot & IOptionsMonitor allows you to read modified parameters even while the application is running.