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); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – 单元测试MVC控制器
- .net – 如何强制硬刷新(ctrl F5)?
- asp.net – 访问asp. VM外部的网络开发服务器
- asp.net-mvc – ASP.Net Html.DropDownList未选择的元素
- ASP.net Web服务与WCF
- asp.net – aspnet_regiis不存在
- asp.net-mvc – 如何构建URL路由?
- asp.net-mvc – 将WebForm视图引擎标记转换为Razor视图引擎
- asp.net-mvc-2 – 使用routeValue从MVC URL中删除索引
- asp.net-mvc – 使用MVCContrib格式进行编辑
推荐文章
站长推荐
- ASP.NET(MVC)服务图像
- 在使用ASP.NET会话时是否可以强制请求并发?
- asp.net-mvc – 如何在Google.Apis调用中使用ASP
- ASP.NET MVC URL在CSS文件中自动解析
- asp.net-mvc – Action()和RenderAction()之间的
- asp.net-mvc – 为什么我需要在asp.net mvc中部分
- MVC3中的IValidatableObject – 客户端验证
- asp.net – 如何使用MVC Razor设置类等html属性?
- asp.net – 通过Button控制Fire AsyncFileUpload
- ASP.NET Webforms验证框架的建议
热点阅读