.Net Core3.0 WEB API中使用FluentValidation验证(批量注入)
为什么要使用FluentValidation
1.在日常的开发中,需要验证参数的合理性,不紧前端需要验证传毒的参数,后端也需要验证参数
2.在领域模型中也应该验证,做好防御性的编程是一种好的习惯(其实以前重来不写的,被大佬教育了一番)
3.FluentValidation是.NET开发的验证框架,开源,主要是简单好用,内置了一些常用的验证器,可以直接使用,扩展也很方便
使用FluentValidation
1.引入FluentValidation.AspNetCoreNuGet包
2.建立需要验证的类
//////创建客户 /// publicclassCreateCustomerDto { //////客户姓名 /// publicstringCustomerName{get;set;} //////客户年龄 /// publicstringCustomerAge{get;set;} //////客户电话 /// publicstringCustomerPhone{get;set;} //////客户地址 /// publicAddressCustomerAddress{get;set;} } //////验证 /// publicclassCreateCustomerDtoValidator:AbstractValidator{ publicCreateCustomerDtoValidator() { RuleFor(x=>x.CustomerName) .NotEmpty() .WithMessage("客户姓名不能为空"); RuleFor(x=>x.CustomerPhone) .NotEmpty() .WithMessage("客户电话不能为空"); } }
3.统一返回验证的信息,ResponseResult为全局统一参数返回的类
//////添加AddFluentValidationErrorMessage /// ///publicDependencyInjectionServiceAddFluentValidationErrorMessage() { _services.Configure (options=> { options.InvalidModelStateResponseFactory=(context)=> { varerrors=context.ModelState .Values .SelectMany(x=>x.Errors .Select(p=>p.ErrorMessage)) .ToList(); varresult=newResponseResult > { StatusCode="00009", Result=errors, Message=string.Join(",",errors.Select(e=>string.Format("{0}",e)).ToList()), IsSucceed=false }; returnnewBadRequestObjectResult(result); }; }); return_dependencyInjectionConfiguration; }
4.注入验证的类
使用builder.RegisterType().As
所以我们使用批量的注入,来减少麻烦,通过反射获取所有的验证的类批量注入
//////添加MVC /// ///publicDependencyInjectionServiceAddMvc() { _services.AddControllers(options=> { options.Filters.Add(typeof(LogHelper)); }).AddJsonOptions(options=> { //忽略循环引用 //options.JsonSerializerOptions.IgnoreReadOnlyProperties=true; }).AddFluentValidation(options=> { options.RunDefaultMvcValidationAfterFluentValidationExecutes=false; varvalidatorList=GetFluentValidationValidator("ConferenceWebApi"); foreach(variteminvalidatorList) { options.RegisterValidatorsFromAssemblyContaining(item); } }); return_dependencyInjectionConfiguration; } /// ///获取所有的FluentValidationValidator的类 /// publicIEnumerableGetFluentValidationValidator(stringassemblyName) { if(assemblyName==null) thrownewArgumentNullException(nameof(assemblyName)); if(string.IsNullOrEmpty(assemblyName)) thrownewArgumentNullException(nameof(assemblyName)); varimplementAssembly=RuntimeHelper.GetAssembly(assemblyName); if(implementAssembly==null) { thrownewDllNotFoundException($"thedllConferenceWebApinotbefound"); } varvalidatorList=implementAssembly.GetTypes().Where(e=>e.Name.EndsWith("Validator")); returnvalidatorList; }
5.使用起来就十分简单了
//////创建客户 /// ////// [HttpPost] publicasyncTask >CreateCustomer([FromBody]CreateCustomerDtoinput) { varcreateCustomerCommand=newCreateCustomerCommand(input.CustomerName,input.CustomerAge,input.CustomerPhone,input.CustomerAddress); await_commandService.SendCommandAsync(createCustomerCommand); varresult=newResponseResult { IsSucceed=true, Result="创建客户成功!" }; returnresult; }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。