This series is a collection of knowledge about ASP .NET Core. It just is my notes.
Part 10: Make an HTTP Request.
Part 12: Authentication and Authorization.
This part shows how to use configuration and how to use Options patterns.
- Default configuration
a. ChaninedConfigurationProvider
b. appsettings.json
c. appsettings.[environment].json
d. app secrets
e. environment variables
f. command-line arguments.
Configuration providers that are added later override the previous key setting.
- JsonConfigurationProvider loads configuration in the following order:
- appsettings.json
- appsetings.{Environment}.json
=> appsetings.{Environment}.json values override keys in appsettings.json
private readonly IConfiguration _configuration;
public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
{
......
}
public WeatherForecast Get()
{
var a = new WeatherForecast
{
// Get value from configureation
Name = _configuration["Name"],
NickName = _configuration["NickName"]
};
return a;
}
- Options pattern to read a related configuration
public class PositionOptions
{
public string Title { get; set; }
public string Name { get; set; }
}
...
var positionOptions = new PositionOptions();
Configuration.GetSection("JsonKeySection").Bind(positionOptions);
OR:
positionOptions = Configuration.GetSection(PositionOptions.Position)
.Get<PositionOptions>();
- Combining service collection
a. How to register configures option in ConfigureServices method
- step 0: create Option class
- step 1: create extension method:
- first param: IServiveCollection
- second param: IConfiguration/ or Action<OptionClass>
- Use: services.Configure method to register configuration
- step 2: use extension method to register the service.
services.Configure<PositionOptions>( config.GetSection(PositionOptions.Position));
services.Configure<ColorOptions>( config.GetSection(ColorOptions.Color));
b. How to get value of Option at another places
- Method 1: Use: IServiceProvider serviceProvider to get option value,
Name = _serviceProvider.GetRequiredService<IOptions<PositionOption>>().Value.Name,
NickName = _serviceProvider.GetRequiredService<IOptions<PositionOption>>().Value.Position
- Method 2:
IOptions<PositionOption> _optionDelegate;
....
// Get value from Option
Name = _optionDelegate.Value.Name,
NickName = _optionDelegate.Value.Position
- File configuration provider
- Json configuration provider
- use: config.AddJsonFile("MyConfig.json", optional: true, reloadOnChange: true)
- to add custom config json file
- This file override settings in the default configuration providers (include environment vars and command-line)
- XML configuration provider
- use: AddXmlFile
- Others config
a. launchsetting.json
b. web.config
A sample of applying options pattern
References:



0 nhận xét:
Đăng nhận xét