.net core 中通过 PostConfigure 验证 Options 参数
.net core 中通過?PostConfigure?驗證 Options 參數
Intro
在 .net core 中配置項推薦用 Options 來實現,有一些參數可能必須是用由用戶來配置,不能直接寫成默認值的參數,這樣就需要就 Options 中的參數做一些校驗,否則程序內部可能就會出現一些意想不到的異常,今天介紹一個比較簡單的,通過 PostConfigure 的方式來實現Options 參數的校驗。
實現
在 PostConfigure 的委托中對所需驗證的參數進行檢查,如果參數不合法就拋一個異常出來, 在依賴注入獲取這個 Option 的時候如果不滿足條件就會拋出一個異常,而通過異常的 stacktrace 就可以看出來是哪里的錯誤了
public static IServiceCollection AddAliyunService(this IServiceCollection serviceCollection, Action<AliyunServiceOption> configAction)
{
if (configAction != null)
{
serviceCollection.Configure(configAction);
}
serviceCollection.PostConfigure<AliyunServiceOption>(options =>
{
if (string.IsNullOrWhiteSpace(options.AccessKeyId))
{
throw new ArgumentNullException(nameof(options.AccessKeyId), $"{nameof(AliyunServiceOption)} {nameof(options.AccessKeyId)} can not be null or empty");
}
if (string.IsNullOrWhiteSpace(options.AccessKeySecret))
{
throw new ArgumentNullException(nameof(options.AccessKeySecret), $"{nameof(AliyunServiceOption)} {nameof(options.AccessKeySecret)} can not be null or empty");
}
});
serviceCollection.TryAddSingleton<IAliyunService, AliyunService>();
return serviceCollection;
}
在 Reference 中給出了一些其他的實現方式,可以參考,在此不做詳細介紹。
.net core 之后版本微軟可能會給出一個更好的驗證方式,詳見 Options Validation: support eager validation
Reference
- https://stackoverflow.com/questions/49651259/asp-net-core-option-validation 
- https://github.com/aspnet/Extensions/issues/459 
- https://www.stevejgordon.co.uk/asp-net-core-2-2-options-validation 
總結
以上是生活随笔為你收集整理的.net core 中通过 PostConfigure 验证 Options 参数的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: asp.net mvc 自定义 page
- 下一篇: .NET做人脸识别并分类
