.net core RESTful Api笔记④
输入验证和Data Annotations
验证三步:验证规则->按照验证顾泽尽行检查->报告错误
定义验证规则:
1.Data Annotation。例:[Required],[MaxLength]等
2.自定义Attribute
3.model实现IValidatableObject接口
按照规则尽行检查
1.ModelState对象是一个Dictionary,他既包含model的状态,也包含了model的绑定信息。
2.他针对每一个提交的属性值的错误信息集合,每当有请求进来的时候,定义好减产规则就会被检查。
验证不通过:
modelState.isValid()返回false。
返回错误:
422:Unprocessable Entity
响应的body里面包含验证的错误信息
Validation Problem Details RFC,asp.netCore 内置了这个标准
修改添加的Dto
Data Annotation
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Rountine.API.Models { public class CompanyAddDto { [Required] [MaxLength(100)] public string Name { get; set; } [MaxLength(500)] public string introduction { get; set; } public ICollection<EmployeeAddDto> Employee { get; set; } = new List<EmployeeAddDto>(); } }
自定义Attribute
EmployeeNoMustDifferentFromFirstNameAttribute:判断员工编号的第一个名字不一样
using Rountine.API.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Rountine.API.ValidationAttributes { public class EmployeeNoMustDifferentFromFirstNameAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var addDto = (EmployeeAddDto)validationContext.ObjectInstance; if (addDto.EmployeeNo == addDto.FirstName) { return new ValidationResult("编号不可以等与名",new[] { nameof(EmployeeAddDto) }) ; } return ValidationResult.Success; } } }
在employeeAddDto上添加属性
using Rountine.API.ValidationAttributes; using Rountion.API.Eneities; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Rountine.API.Models { [EmployeeNoMustDifferentFromFirstName] public class EmployeeAddDto { public string EmployeeNo { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public Gender Gender { get; set; } public DateTime DateOfBirth { get; set; } } }
实现IValidatableObject接口暂时不写,感觉不如上面两种