ASP.NET Core WebApi Post/IValidatableObjext/添加类级别验证/自定义错误报告
Post 从body提交(json或其他格式)
[HttpPost]
public async Task<ActionResult<CompanyDto>> CreateCompany([FromBody] CompanyAddDto companyAddDto)
{
var entity = _mapper.Map<Company>(companyAddDto);
_companyRepository.AddCompany(entity);//执行到这里仅仅提交到了DbContext,还没有保存到数据库
await _companyRepository.saveAsync();
var dot = _mapper.Map<CompanyDto>(entity);
//创建成功定位到GetCompanie方法上,传入值
return CreatedAtRoute(nameof(GetCompanie), routeValues: new { companyId = dot.Id }, dot);
}
实现IValidatableObjext接口添加自定义验证
[CompanyNameMustLessThanNighteenAttribute]
public class CompanyAddDto:IValidatableObject
{
//ID不需要的,它要在api后台自动生成,当然客户端提供也是可以的
//公司类,公司输出类,公司添加类,分别创建(便于以后改动!)
[Display(Name="Company Name!")]
[Required(ErrorMessage ="{0} is Required!!!!!")] //{0} is name
public string Name { get; set; }
public string Introduction { get; set; }
//add user Validation with complex
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Name.Length >= 15)
{
yield return new ValidationResult(errorMessage: "Errormsg", memberNames: new[] { nameof(Name) });
}
}
//the other validation : FluentValidation(recommendation)
//1.easy create complex validation
//2.validation rules seprate form Model
//3.to unit Test
}
添加类级别的验证
类前面添加[CompanyNameMustLessThanNighteenAttribute]
实现ValidationAttribute
//Define user's Validation for Class Level
public class CompanyNameMustLessThanNighteenAttribute:ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var addDto = value as CompanyAddDto;//another method:validationContext.ObjectInstance
if (addDto.Name.Length >= 15)
{
return new ValidationResult(errorMessage: "名字太长了");
}
return ValidationResult.Success;
}
}
自定义错误信息和错误报告.ConfigureApiBehaviorOptions
services.AddControllers(
configure: setup =>
{
setup.ReturnHttpNotAcceptable = true;
// setup.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
}
)
.AddXmlDataContractSerializerFormatters()
.ConfigureApiBehaviorOptions(
setup => setup.InvalidModelStateResponseFactory = context =>
{
var problemDetails = new ValidationProblemDetails(context.ModelState)
{
Type = "www.baidu.com",
Title = "error",
Status = StatusCodes.Status422UnprocessableEntity,
Detail = "请看详细信息",
Instance = context.HttpContext.Request.Path
};
problemDetails.Extensions.Add("traceId", context.HttpContext.TraceIdentifier);
return new UnprocessableEntityObjectResult(problemDetails)
{
ContentTypes = { "application/problem+json" }
};
}
);