加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-core-mvc – MVC 6配置验证

发布时间:2020-12-16 07:25:28 所属栏目:asp.Net 来源:网络整理
导读:在MVC 6项目中,我有以下配置文件…… { "ServiceSettings" : { "Setting1" : "Value" }} ……以及下面的课…… public class ServiceSettings{ public Setting1 { get; set; }} 在Startup类的ConfigureServices方法中,我添加了以下代码行… services.Configu
在MVC 6项目中,我有以下配置文件……

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

……以及下面的课……

public class ServiceSettings
{
  public Setting1
  {
    get;

    set;
  }
}

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

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

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

解决方法

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

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

    EnforceRequiredStrings(settings);
})

以及启动时的以下内容:

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);
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读