اعتبارسنجی Options ✅🔍
ءOptions validation امکان اعتبارسنجی مقدارهای options را فراهم میکند.
فایل appsettings.json زیر را در نظر بگیرید:
{
"MyConfig": {
"Key1": "My Key One",
"Key2": 10,
"Key3": 32
}
}کلاس زیر برای Bind شدن به بخش "MyConfig" استفاده میشود و چند قانون DataAnnotations را اعمال میکند:
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; }
}
کد زیر:
ءAddOptions را فراخوانی میکند تا <OptionsBuilder<MyConfigOptions را دریافت کند که به کلاس MyConfigOptions Bind میشود.
ءValidateDataAnnotations را فراخوانی میکند تا اعتبارسنجی با استفاده از DataAnnotations فعال شود.
builder.Services.AddOptions<MyConfigOptions>()
.Bind(builder.Configuration.GetSection(MyConfigOptions.MyConfig))
.ValidateDataAnnotations();
متد ValidateDataAnnotations در پکیج Microsoft.Extensions.Options.DataAnnotations قرار دارد. برای web appهایی که از SDK نوع Microsoft.NET.Sdk.Web استفاده میکنند، این پکیج بهطور ضمنی از shared framework مرجع میشود.
کد زیر مقدارهای configuration یا خطاهای validation را نمایش میدهد:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IOptions<MyConfigOptions> _config;
public HomeController(IOptions<MyConfigOptions> config,
ILogger<HomeController> logger)
{
_config = config;
_logger = logger;
try
{
var configValue = _config.Value;
}
catch (OptionsValidationException ex)
{
foreach (var failure in ex.Failures)
{
_logger.LogError(failure);
}
}
}
public ContentResult Index()
{
string msg;
try
{
msg = $"Key1: {_config.Value.Key1} \n" +
$"Key2: {_config.Value.Key2} \n" +
$"Key3: {_config.Value.Key3}";
}
catch (OptionsValidationException optValEx)
{
return Content(optValEx.Message);
}
return Content(msg);
}
}
کد زیر یک قانون پیچیدهتر اعتبارسنجی را با استفاده از یک delegate اعمال میکند:
builder.Services.AddOptions<MyConfigOptions>()
.Bind(builder.Configuration.GetSection(MyConfigOptions.MyConfig))
.ValidateDataAnnotations()
.Validate(config =>
{
if (config.Key2 != 0)
{
return config.Key3 > config.Key2;
}
return true;
}, "Key3 must be > than Key2."); // Failure message.