如何使用ASP.NET Core 2.2中的IValidateOptions验证配置设置?

编程入门 行业动态 更新时间:2024-10-27 05:26:49
本文介绍了如何使用ASP.NET Core 2.2中的IValidateOptions验证配置设置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

Microsoft的ASP.NET Core文档简短地提到,您可以实现 IValidateOptions< TOptions> 来验证来自appsettings.json的配置设置,但未提供完整的示例. IValidateOptions 应该如何使用?更具体地说:

Microsoft's ASP.NET Core documentation briefly mentions that you can implement IValidateOptions<TOptions> to validate configuration settings from appsettings.json, but a complete example is not provided. How is IValidateOptions intended to be used? More specifically:

  • 您在哪里连接验证器类?
  • 如果验证,您如何记录一条有用的消息来解释问题所在失败了吗?

我实际上已经找到了解决方案.我正在发布我的代码,因为此时我在Stack Overflow上找不到任何提及 IValidateOptions 的地方.

I have actually found a solution already. I'm posting my code since I can't find any mention of IValidateOptions on Stack Overflow at this time.

推荐答案

我最终在提交在其中添加了选项验证功能的地方.与asp核心中的许多内容一样,答案是将您的验证器添加到DI容器中,它将自动被使用.

I eventually found an example of how this is done in the commit where the options validation feature was added. As with so many things in asp core, the answer is to add your validator to the DI container and it will automatically be used.

通过这种方法, PolygonConfiguration 在验证后进入DI容器,并可以注入到需要它的控制器中.我更喜欢将 IOptions< PolygonConfiguration> 注入到我的控制器中.

With this approach the PolygonConfiguration goes into the DI container after validation and can be injected into the controllers that need it. I prefer this to injecting IOptions<PolygonConfiguration> into my controllers.

似乎验证代码在容器中第一次请求 PolygonConfiguration 的实例时运行(即,在实例化控制器时).在启动过程中更早地进行验证可能会很好,但是我对此感到满意.

It appears that the validation code runs the first time an instance of PolygonConfiguration is requested from the container (i.e. when the controller is instantiated). It might be nice to validate earlier during startup, but I'm satisfied with this for now.

这就是我最终要做的:

public class Startup { public Startup(IConfiguration configuration, ILoggerFactory loggerFactory) { Configuration = configuration; Logger = loggerFactory.CreateLogger<Startup>(); } public IConfiguration Configuration { get; } private ILogger<Startup> Logger { get; } public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //Bind configuration settings services.Configure<PolygonConfiguration>(Configuration.GetSection(nameof(PolygonConfiguration))); //Add validator services.AddSingleton<IValidateOptions<PolygonConfiguration>, PolygonConfigurationValidator>(); //Validate configuration and add to DI container services.AddSingleton<PolygonConfiguration>(container => { try { return container.GetService<IOptions<PolygonConfiguration>>().Value; } catch (OptionsValidationException ex) { foreach (var validationFailure in ex.Failures) Logger.LogError($"appSettings section '{nameof(PolygonConfiguration)}' failed validation. Reason: {validationFailure}"); throw; } }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { ... } }

appSettings.json,其中包含一些有效值和无效值

appSettings.json with some valid and invalid values

{ "PolygonConfiguration": { "SupportedPolygons": [ { "Description": "Triangle", "NumberOfSides": 3 }, { "Description": "Invalid", "NumberOfSides": -1 }, { "Description": "", "NumberOfSides": 6 } ] } }

验证器类本身

public class PolygonConfigurationValidator : IValidateOptions<PolygonConfiguration> { public ValidateOptionsResult Validate(string name, PolygonConfiguration options) { if (options is null) return ValidateOptionsResult.Fail("Configuration object is null."); if (options.SupportedPolygons is null || options.SupportedPolygons.Count == 0) return ValidateOptionsResult.Fail($"{nameof(PolygonConfiguration.SupportedPolygons)} collection must contain at least one element."); foreach (var polygon in options.SupportedPolygons) { if (string.IsNullOrWhiteSpace(polygon.Description)) return ValidateOptionsResult.Fail($"Property '{nameof(Polygon.Description)}' cannot be blank."); if (polygon.NumberOfSides < 3) return ValidateOptionsResult.Fail($"Property '{nameof(Polygon.NumberOfSides)}' must be at least 3."); } return ValidateOptionsResult.Success; } }

以及配置模型

public class Polygon { public string Description { get; set; } public int NumberOfSides { get; set; } } public class PolygonConfiguration { public List<Polygon> SupportedPolygons { get; set; } }

更多推荐

如何使用ASP.NET Core 2.2中的IValidateOptions验证配置设置?

本文发布于:2023-11-15 07:55:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1592569.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   ASP   NET   IValidateOptions   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!