How to validate configuration settings using IValidateOptions in ASP.NET Core 2.2?

前端 未结 4 2153
[愿得一人]
[愿得一人] 2021-02-14 15:57

Microsoft\'s ASP.NET Core documentation briefly mentions that you can implement IValidateOptions to validate configuration settings from appsettings

4条回答
  •  梦如初夏
    2021-02-14 16:21

    Just build a lib for integrate FluentValidation with Microsoft.Extensions.Options.

    https://github.com/iron9light/FluentValidation.Extensions

    The nuget is here: https://www.nuget.org/packages/IL.FluentValidation.Extensions.Options/

    Sample:

    public class MyOptionsValidator : AbstractValidator {
        // ...
    }
    
    using IL.FluentValidation.Extensions.Options;
    
    // Registration
    services.AddOptions("optionalOptionsName")
        .Configure(o => { })
        .Validate(); // ❗ Register validator type
    
    // Consumption
    var monitor = services.BuildServiceProvider()
        .GetService>();
    
    try
    {
        var options = monitor.Get("optionalOptionsName");
    }
    catch (OptionsValidationException ex)
    {
    }
    

提交回复
热议问题