.Net Core3.0 WEB API 中使用FluentValidation验证,实现批量注入
为什么要使用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>();比较麻烦每次新增都需要添加一次注入
所以我们使用批量的注入,来减少麻烦,通过反射获取所有的验证的类批量注入
/// <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;
}
FluentValidation学习的资料
感谢大佬们的分享,零度编程中的教程非常的全面,包括了许多的验证器的使用,记不住时直接可以翻阅查看
零度编程:https://www.xcode.me/post/5849
Lamond Lu:https://www.cnblogs.com/lwqlun/p/10311945.html
.Net Core3.0 WEB API 中使用FluentValidation验证,实现批量注入的更多相关文章
- Web API中的模型验证
一.模型验证的作用 在ASP.NET Web API中,我们可以使用 System.ComponentModel.DataAnnotations 命名空间中的属性为模型上的属性设置验证规则. 一个模型 ...
- Web API中的模型验证Model Validation
数据注释 在ASP.NET Web API中,您可以使用System.ComponentModel.DataAnnotations命名空间中的属性为模型上的属性设置验证规则. using System ...
- ASP.NET Web API 中的返回数据格式以及依赖注入
本篇涉及ASP.NET Web API中的返回数据合适和依赖注入. 获取数据 public IEnumerable<Food> Get() { var results = reop.Get ...
- .net core3.1 web api中使用newtonsoft替换掉默认的json序列化组件
在微软的文档中,有着较为详细的替换教程 https://docs.microsoft.com/zh-cn/aspnet/core/web-api/advanced/formatting?view=as ...
- 【ASP.NET Web API教程】4.3 ASP.NET Web API中的异常处理
原文:[ASP.NET Web API教程]4.3 ASP.NET Web API中的异常处理 注:本文是[ASP.NET Web API系列教程]的一部分,如果您是第一次看本系列教程,请先看前面的内 ...
- Web APi 2.0优点和特点?在Web APi中如何启动Session状态?
前言 曾几何时,微软基于Web服务技术给出最流行的基于XML且以扩展名为.asmx结尾的Web Service,此服务在.NET Framework中风靡一时同时也被.NET业界同仁所青睐,几年后在此 ...
- Entity Framework 6 Recipes 2nd Edition(9-3)译->找出Web API中发生了什么变化
9-3. 找出Web API中发生了什么变化 问题 想通过基于REST的Web API服务对数据库进行插入,删除和修改对象图,而不必为每个实体类编写单独的更新方法. 此外, 用EF6的Code Fri ...
- 在ASP.NET Web API中使用OData
http://www.alixixi.com/program/a/2015063094986.shtml 一.什么是ODataOData是一个开放的数据协议(Open Data Protocol)在A ...
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【五】——在Web Api中实现Http方法(Put,Post,Delete)
系列导航地址http://www.cnblogs.com/fzrain/p/3490137.html 前言 在Web Api中,我们对资源的CRUD操作都是通过相应的Http方法来实现——Post(新 ...
随机推荐
- 列表[‘hello’ , ‘python’ ,’!’ ] 用多种方法拼接,并输出’hello python !’ 以及join()在python中的用法简介
列表[‘hello’ , ‘python’ ,’!’ ] 用多种方法拼接,并输出’hello python !’ 使用字符串链接的四种方法都可以创建 字符串拼接一共有四种方法,也可以应用到列表的拼接中 ...
- 【Spring Boot】java.lang.NoSuchMethodError: org.springframework.web.util.UrlPathHelper.getLookupPathForRequest(Ljavax/servlet/http/HttpServletRequest;Ljava/lang/String;)Ljava/lang/String;
Digest:今天Spring Boot 应用启动成功,访问接口出现如下错误,不知到导致问题关键所在,记录一下这个问题. 浏览器报500错误 项目代码如下 Controller.java packag ...
- Linux 命令之 crontab
crontab 简介 crontab 主要用于需要管理周期执行定时任务的场景 crontab 安装 (有些系统默认已经带了 crontab,无需安装的朋友可以直接跳过本节) 安装: yum insta ...
- 前端技术之:通过plop生成Controller的方法与步骤
# Controller的生成 开发者可以通过plop命令生成各种类型的控制器类(Normal.Restful.View), 以下是示例生成步骤. 1. 执行以下命令: plop controller ...
- Windows 10 与 kali 双系统安装
一.教程中用到的工具如下: 1.kali 2019镜像, 2.U盘 现在最低也有8G吧 3.软碟通 ,U盘刻录工具 4.win 10系统要留出一个空的硬盘,哪个盘的空间比较大可以压缩出大概100G的空 ...
- 一个自动管理项目的Makefile(C语言)
Linux 是所有嵌入式软件工程师绕不过去的坎, makefile 是在Linux系统中绕不过去的坎. 花了几天时间初步学习和了解了makefile 的作用以及功能,并且制作了一个通用型的makefi ...
- 使用VM虚拟机安装Linux系统详细流程
最近新换了个电脑,所以需要重新安装虚拟机和Linux系统,话不多说,看流程吧 1.安装vm,这个就不说了,打开VM 2.点击安装虚拟机 3.选择自定义安装 4.选择稍后安装 5.选择要安装的系统 6. ...
- NOIP模(ka)拟(chang)测试30 考试报告
应得分:300 实得分:210 毒瘤卡常出题人,卡掉90分! T1 Return 开个副本数组sort一下,unique去重就可以啦.时间复杂度$ O(nlog2(n)) $ T2 One 其实就是约 ...
- TCP协议--TCP三次握手和四次挥手
TCP三次握手和四次挥手 TCP有6种标示:SYN(建立联机) ACK(确认) PSH(传送) FIN(结束) RST(重置) URG(紧急) 一.TCP三次握手 第一次握手 客户端向服务器发出连 ...
- 中文企业云操作系统 CecOS
CecOS介绍 CecOS(原中文企业云操作系统.第一个版本基于oVirt 3.0,后续在此基础上不断升级迭代拓展至今,已形成基于基础底层和应用功能拓展集成在内的10款产品和四大平台),旨在通过先进的 ...