选项模式在 ASP.NET Core 中使用类来提供对相关配置设置的强类型访问。通过将配置设置隔离到单独的类,应用程序遵循封装和关注点分离的原则。封装确保依赖于配置的类仅依赖于其使用的设置;关注点分离则确保应用的不同部分的设置互不依赖或耦合。此外,选项模式还提供了验证配置数据的机制。
三种IOptions:
下面是代码文件:
Program.cs
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOptions().BindConfiguration(“Setting”);
var app = builder.Build();
app.Services.GetService>()?.OnChange((setting, name) =>
{
app.Logger.LogInformation(setting.Value);
});
app.MapGet(“/opt1”, (IOptions option) =>
{
app.Logger.LogInformation(“opt1”);
return option.Value;
});
app.MapGet(“/opt2”, (IOptionsSnapshot option) =>
{
app.Logger.LogInformation(“opt2”);
return option.Value;
});
app.MapGet(“/opt3”, (IOptionsMonitor option) =>
{
app.Logger.LogInformation(“opt3”);
return option.CurrentValue;
});
app.Run();
class Setting
{
public string Name { get; set; }
public string Value { get; set; }
}
appsettings.json
{
“Logging”: {
“LogLevel”: {
“Default”: “Information”,
“Microsoft.AspNetCore”: “Warning”
}
},
“AllowedHosts”: “*”,
“Setting”: {
“Name”: “key”,
“Value”: “1234567890”
}
}
OptionDemo.http
@OptionDemo_HostAddress = http://localhost:5064
GET {{OptionDemo_HostAddress}}/opt1
Accept: application/json
#
GET {{OptionDemo_HostAddress}}/opt2
Accept: application/json
#
GET {{OptionDemo_HostAddress}}/opt3
Accept: application/json
#
打开OptionDemo.http,点击Opt1,Opt2,Opt3的“发送请求”,结果如下:
把 appsettings.json中的Setting的Value改成“1234567890ABCD”,结果如下:
请求Opt1结果:
请求Opt2结果:
请求Opt3结果:
验证:
可以通过Validate()方法对Options进行验证,目前有两种验证点,一个是服务启动时,即有ValidateOnStart方法;另外一种是在使用这个Options时,即不写ValidateOnStart方法。
builder.Services.AddOptions()
.BindConfiguration(“Setting”)
.ValidateOnStart()
.Validate(setting =>
{
return !string.IsNullOrWhiteSpace(setting.Name) && !string.IsNullOrWhiteSpace(setting.Value);
}, “Setting配置有误”);
触发错误如下:
利用Validate是自定义验证,当然也可以利用DataAnnotations进行验证,代码如下:
builder.Services.AddOptions()
.BindConfiguration(“Setting”)
.ValidateDataAnnotations();
触发错误如下:
声明:文中观点不代表本站立场。本文传送门:https://eyangzhen.com/424642.html