繁体   English   中英

ASP.Net-Core 选项验证

[英]ASP.Net-Core option validation

我已经为IServiceCollection编写了一个扩展方法,它接受一个选项委托。 我的问题是我必须首先验证配置的选项(例如过滤掉null值),因为继续和实例化依赖于这些选项的服务是不安全的。

public static class ServiceCollectionExtensions {
    public static void AddServices(
        this IServiceCollection services,
        Action<ServiceOptions> configureOptions)
    {
        // Configure service
        services.AddSingleton<IAbstraction, Implementation>();

        // Validate options here...

        // Configure options
        services.Configure(configureOptions);
    }
}

如何在不调用委托configureOptions情况下验证选项是否正确指定? 我不想依赖ServiceOptions默认值,因为我想强制执行一些设置。

ASP.NET 核心 2.2+

文档

OptionsBuilder上有一个验证方法。 验证将在第一次使用IOptions<T>.Value属性时进行。 如果无效,它将抛出OptionsValidationException 在这里跟踪热切的验证。

public static class ServiceCollectionExtensions {
    public static void AddServices(
        this IServiceCollection services,
        Action<ServiceOptions> configureOptions)
    {
        // Configure service
        services.AddSingleton<IAbstraction, Implementation>();

        // Configure and validate options
        services.AddOptions<ServiceOptions>()
            .Configure(configureOptions)
            .Validate(options => {
                // Take the fully configured options and return validity...
                return options.Option1 != null;
            });
    }
}

或者, .ValidateDataAnnotations()也可用,因此尊重数据注释属性。

ASP.NET 核心 2.0+

从 ASP.NET Core 2.0 开始, PostConfigure非常适合。 这个函数也需要一个配置委托,但最后执行,所以一切都已经配置好了。

public static class ServiceCollectionExtensions {
    public static void AddServices(
        this IServiceCollection services,
        Action<ServiceOptions> configureOptions)
    {
        // Configure service
        services.AddSingleton<IAbstraction, Implementation>();

        // Configure and validate options
        services.Configure(configureOptions);
        services.PostConfigure<ServiceOptions>(options => {
            // Take the fully configured options and run validation checks...
            if (options.Option1 == null) {
                throw new Exception("Option1 has to be specified");
            }
        });
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM