MVC 6配置验证

时间:2015-09-25 14:07:34

标签: asp.net-core-mvc

在MVC 6项目中,我有以下配置文件......

{
  "ServiceSettings" :
  {
    "Setting1" : "Value"
  }
}

......以及以下课程......

public class ServiceSettings
{
  public Setting1
  {
    get;

    set;
  }
}

ConfigureServices类的Startup方法中,我添加了以下代码行...

services.Configure<ServiceSettings>(Configuration.GetConfigurationSection("ServiceSettings"));

如果需要Setting1的值,我该如何验证?我可以在实际使用IOptions<ServiceSettings>实例时进行验证,但如果服务操作需要Setting1的值,我想尽早捕获它而不是进一步下游。旧的ConfigurationSection对象允许您指定在某些内容无效的情况下在读取配置数据时抛出异常的规则。

4 个答案:

答案 0 :(得分:5)

您可以执行以下操作:

services.Configure<ServiceSettings>(serviceSettings =>
{
    // bind the newed-up type with the data from the configuration section
    ConfigurationBinder.Bind(serviceSettings, Configuration.GetConfigurationSection(nameof(ServiceSettings)));

    // modify/validate these settings if you want to
});

// your settings should be available through DI now

答案 1 :(得分:2)

我将[Required]置于ServiceSettings的任何强制属性上,并在Startup.ConfigureServices中添加了以下内容:

services.Configure<ServiceSettings>(settings =>
{
    ConfigurationBinder.Bind(Configuration.GetSection("ServiceSettings"), settings);

    EnforceRequiredStrings(settings);
})

以下Startup

private static void EnforceRequiredStrings(object options)
{
    var properties = options.GetType().GetTypeInfo().DeclaredProperties.Where(p => p.PropertyType == typeof(string));
    var requiredProperties = properties.Where(p => p.CustomAttributes.Any(a => a.AttributeType == typeof(RequiredAttribute)));

    foreach (var property in requiredProperties)
    {
        if (string.IsNullOrEmpty((string)property.GetValue(options)))
            throw new ArgumentNullException(property.Name);
    }
}

答案 2 :(得分:2)

使用ASP.Net-Core 2.0验证选项的简洁方法

netcore2.0开始,PostConfigure非常合适。此函数也接受配置委托,但最后执行,因此所有内容都已配置。

// Configure options as usual
services.Configure<MyOptions>(Configuration.GetSection("section"));

// Then, immediately afterwards define a delegate to validate the FINAL options later
services.PostConfigure<MyOptions>(myOptions => {
    // Take the fully configured myOptions and run validation checks...
    if (myOptions.Option1 == null) {
        throw new Exception("Option1 has to be specified");
    }
});

答案 3 :(得分:0)

如果不怕向配置对象添加更多代码,则可以在启动时实现验证,如 Andrew Lock blog 中所述。他创建了 NuGet 包以避免自己添加代码。 如果你想探索更多的可能性,还有 ConfigurationValidation 包提供了一些扩展的配置验证功能(自以为是:我是作者)。 如果您将 FluentValidation 用于某事,there is possibility 也将其用于配置验证。