.NET 云原生架構(gòu)師訓(xùn)練營(yíng)(模塊二 基礎(chǔ)鞏固 配置)--學(xué)習(xí)筆記
2.2.3 核心模塊--配置
IConfiguration
Options
ASP.NET Core 中的配置:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/?view=aspnetcore-5.0
IConfiguration
IConfiguration 的使用
層級(jí)對(duì)象配置到 key-value 鍵值對(duì)轉(zhuǎn)換
通過(guò)環(huán)境變量修改日志級(jí)別
通過(guò)命令行修改日志級(jí)別
IConfiguration 的使用
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
新增 ConfigController.cs
namespace HelloApi.Controllers
{
[ApiController]
[Route("[controller]")]
public class ConfigController : Controller
{
private readonly IConfiguration _configuration;
public ConfigController(IConfiguration configuration)
{
_configuration = configuration;
}
[HttpGet]
public IActionResult GetConfigurations()
{
var result = new List<string>();
foreach (var key in _configuration.AsEnumerable())
{
result.Add($"Key: {key.Key}, value: {key.Value}");
}
return Ok(result);
}
}
}
啟動(dòng)程序,訪問(wèn):https://localhost:5001/config
不僅得到 appsettings.json 的配置, 還可以得到環(huán)境變量配置
可以在 ConfigureAppConfiguration 中清除所有配置,再添加自己需要的配置,后面添加的配置會(huì)覆蓋前面的配置
.ConfigureAppConfiguration((hostingContext, config) =>
{
config.Sources.Clear();
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
})
啟動(dòng)程序,訪問(wèn):https://localhost:5001/config
這樣可以得到自己添加的配置
層級(jí)對(duì)象配置到 key-value 鍵值對(duì)轉(zhuǎn)換
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
通過(guò)冒號(hào)讀取下一級(jí)配置(Windows),Linux 上通過(guò)下劃線
[HttpGet]
public IActionResult GetConfigurations()
{
var result = new List<string>();
//foreach (var key in _configuration.AsEnumerable())
//{
// result.Add($"Key: {key.Key}, value: {key.Value}");
//}
return Content(string.Format("Default Log Level: {0}", _configuration["Logging:LogLevel:Default"]));
}
啟動(dòng)程序,輸出如下:
Default Log Level: Debug
通過(guò)環(huán)境變量修改日志級(jí)別
在 launcSettings.json 中添加 Trace 日志級(jí)別
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development",
"Logging__LogLevel__Default": "Trace"
}
在 CreateHostBuilder 的時(shí)候添加環(huán)境變量配置
config.AddEnvironmentVariables();
啟動(dòng)程序,輸出如下:
Default Log Level: Trace
通過(guò)命令行修改日志級(jí)別
CreateHostBuilder
config.AddCommandLine(source =>
{
source.Args = args;
});
在命令行中設(shè)置
set Logging__LogLevel__Default=Warning
Options
通過(guò) ConfigurationBinder 操作 Options
通過(guò) Configure 綁定 Option
通過(guò) ConfigurationBinder 操作 Options
新建 MyOption.cs
namespace HelloApi
{
public class MyOption
{
public string Name { get; set; }
public int Age { get; set; }
}
}
在 appsettings.json 中新增一個(gè)節(jié)點(diǎn)
"MyOption": {
"Name": "Mingson",
"Age": 25
},
在 ConfigureServices 中綁定
var myOption = new MyOption();
Configuration.GetSection("MyOption").Bind(myOption);
// 單例注入到全局中
services.AddSingleton(myOption);
在 ConfigController 中注入,與獲取
private readonly MyOption _myOption;
public ConfigController(IConfiguration configuration, MyOption myOption)
{
_configuration = configuration;
_myOption = myOption;
}
[HttpGet("option")]
public IActionResult GetOption()
{
return Ok(_myOption);
}
啟動(dòng)程序,訪問(wèn):https://localhost:5001/config/option
輸出如下:
{"name":"Mingson","age":25}
通過(guò) Get 的方式
myOption = Configuration.GetSection("MyOption").Get();
通過(guò) Configure 綁定 Option
IOptions
IOptions
?被注冊(cè)為 singletone,不支持為可命名的配置 IOptionsSnapshot
?被注冊(cè)為 scoped,支持為可命名的配置 IOptionsMonitor
?被注冊(cè)為 singletone,會(huì)被通知,支持重載配置,支持為可命名的配置
IOptions
// 直接注入到容器中
services.Configure(Configuration.GetSection("MyOption"));
通過(guò) IOptions 注入
public ConfigController(IConfiguration configuration, IOptions myOption)
{
_configuration = configuration;
_myOption = myOption.Value;
}
啟動(dòng)程序可以得到同樣的輸出
IOptionsSnapshot
public ConfigController(IConfiguration configuration, IOptionsSnapshot myOption)
{
_configuration = configuration;
_myOption = myOption.Value;
}
啟動(dòng)程序,修改配置,刷新瀏覽器,可以獲取到修改后的配置
可命名的配置
appsettings.json
"Jack": {
"Name": "Jack",
"Age": 16
},
"Peter": {
"Name": "Peter",
"Age": 18
}
MyOption.cs
public const string PETER = "Peter";
public const string JACK = "Jack";
ConfigureServices
services.Configure("Peter", Configuration.GetSection("Peter"));
services.Configure("Jack", Configuration.GetSection("Jack"));
ConfigController
_myOption = myOption.Get(MyOption.PETER);
_myOption = myOption.Get(MyOption.JACK);
啟動(dòng)程序即可讀取不同命名的配置
IOptionsMonitor
public ConfigController(IConfiguration configuration, IOptionsMonitor myOption)
{
_configuration = configuration;
_myOption = myOption.CurrentValue;
// 配置變化處理
myOption.OnChange(option =>
{
});
}
option 驗(yàn)證
屬性驗(yàn)證標(biāo)簽
namespace HelloApi
{
public class MyConfigOptions
{
public const string MyConfig = "MyConfig";
[RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$")]
public string Key1 { get; set; }
[Range(0, 1000, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
public int Key2 { get; set; }
public int Key3 { get; set; }
}
}
綁定后校驗(yàn)
ConfigureServices
services.AddOptions<MyOption>().Bind(Configuration.GetSection("MyOption")).ValidateDataAnnotations();
MyOption
[Range(1, 20)]
public int Age { get; set; }
啟動(dòng)程序,輸出如下:
OptionsValidationException: DataAnnotation validation failed for members: 'Age' with the error: 'The field Age must be between 1 and 20.'.
PostConfigure
當(dāng)配置被讀取出來(lái)的時(shí)候會(huì)被執(zhí)行
services.PostConfigure(option =>
{
if (option.Age == 20)
{
option.Age = 19;
}
});
GitHub源碼鏈接:
https://github.com/MINGSON666/Personal-Learning-Library/tree/main/ArchitectTrainingCamp/HelloApi
課程鏈接
.NET云原生架構(gòu)師訓(xùn)練營(yíng)講什么,怎么講,講多久
