MVC 6配置验证

Jas*_*ier 4 asp.net-core-mvc

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

{
  "ServiceSettings" :
  {
    "Setting1" : "Value"
  }
}
Run Code Online (Sandbox Code Playgroud)

......以及下面的课......

public class ServiceSettings
{
  public Setting1
  {
    get;

    set;
  }
}
Run Code Online (Sandbox Code Playgroud)

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

services.Configure<ServiceSettings>(Configuration.GetConfigurationSection("ServiceSettings"));
Run Code Online (Sandbox Code Playgroud)

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

Kir*_*lla 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
Run Code Online (Sandbox Code Playgroud)