.Net Core3.0 WEB API中使用FluentValidation验证(批量注入)
程序员文章站
2022-03-21 12:30:30
为什么要使用fluentvalidation
1.在日常的开发中,需要验证参数的合理性,不紧前端需要验证传毒的参数,后端也需要验证参数
2.在领域模型中也应该验证,做好防御性的...
为什么要使用fluentvalidation
1.在日常的开发中,需要验证参数的合理性,不紧前端需要验证传毒的参数,后端也需要验证参数
2.在领域模型中也应该验证,做好防御性的编程是一种好的习惯(其实以前重来不写的,被大佬教育了一番)
3.fluentvalidation 是.net 开发的验证框架,开源,主要是简单好用,内置了一些常用的验证器,可以直接使用,扩展也很方便
使用fluentvalidation
1.引入fluentvalidation.aspnetcore nuget包
2.建立需要验证的类
/// <summary> /// 创建客户 /// </summary> public class createcustomerdto { /// <summary> /// 客户姓名 /// </summary> public string customername { get; set; } /// <summary> /// 客户年龄 /// </summary> public string customerage { get; set; } /// <summary> /// 客户电话 /// </summary> public string customerphone { get; set; } /// <summary> /// 客户地址 /// </summary> public address customeraddress { get; set; } } /// <summary> /// 验证 /// </summary> public class createcustomerdtovalidator : abstractvalidator<createcustomerdto> { public createcustomerdtovalidator() { rulefor(x => x.customername) .notempty() .withmessage("客户姓名不能为空"); rulefor(x => x.customerphone) .notempty() .withmessage("客户电话不能为空"); } }
3.统一返回验证的信息,responseresult为全局统一参数返回的类
/// <summary> /// 添加addfluentvalidationerrormessage /// </summary> /// <returns></returns> public dependencyinjectionservice addfluentvalidationerrormessage() { _services.configure<apibehavioroptions>(options => { options.invalidmodelstateresponsefactory = (context) => { var errors = context.modelstate .values .selectmany(x => x.errors .select(p => p.errormessage)) .tolist(); var result = new responseresult<list<string>> { statuscode = "00009", result = errors, message = string.join(",", errors.select(e => string.format("{0}", e)).tolist()), issucceed = false }; return new badrequestobjectresult(result); }; }); return _dependencyinjectionconfiguration; }
4.注入验证的类
使用builder.registertype().as<ivalidator>();比较麻烦每次新增都需要添加一次注入
所以我们使用批量的注入,来减少麻烦,通过反射获取所有的验证的类批量注入
/// <summary> /// 添加mvc /// </summary> /// <returns></returns> public dependencyinjectionservice addmvc() { _services.addcontrollers(options => { options.filters.add(typeof(loghelper)); }).addjsonoptions(options => { //忽略循环引用 //options.jsonserializeroptions.ignorereadonlyproperties = true; }).addfluentvalidation(options => { options.rundefaultmvcvalidationafterfluentvalidationexecutes = false; var validatorlist = getfluentvalidationvalidator("conferencewebapi"); foreach (var item in validatorlist) { options.registervalidatorsfromassemblycontaining(item); } }); return _dependencyinjectionconfiguration; } /// <summary> /// 获取所有的fluentvalidation validator的类 /// </summary> public ienumerable<type> getfluentvalidationvalidator(string assemblyname) { if (assemblyname == null) throw new argumentnullexception(nameof(assemblyname)); if (string.isnullorempty(assemblyname)) throw new argumentnullexception(nameof(assemblyname)); var implementassembly = runtimehelper.getassembly(assemblyname); if (implementassembly == null) { throw new dllnotfoundexception($"the dll conferencewebapi not be found"); } var validatorlist = implementassembly.gettypes().where(e => e.name.endswith("validator")); return validatorlist; }
5.使用起来就十分简单了
/// <summary> /// 创建客户 /// </summary> /// <param name="input"></param> /// <returns></returns> [httppost] public async task<responseresult<string>> createcustomer([frombody] createcustomerdto input) { var createcustomercommand = new createcustomercommand(input.customername,input.customerage,input.customerphone,input.customeraddress); await _commandservice.sendcommandasync(createcustomercommand); var result = new responseresult<string> { issucceed = true, result = "创建客户成功!" }; return result; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: THINKPHP5.1 Config的配置与获取详解
下一篇: 美国考虑将中芯国际列入“实体清单”