利用InvalidModelStateResponseFactory
官网推荐做法 覆盖ModelState管理的默认行为,只有在数据验证失败时才会执行
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = (context) =>
{
//参数验证
services.Configure<ApiBehaviorOptions>(options =>
{
//只有在数据验证失败时才会执行
options.InvalidModelStateResponseFactory = (context) =>
{
var errors = context.ModelState.Select(f => new KeyValuePair<string, IEnumerable<string>>(f.Key, f.Value.Errors.Select(e => e.ErrorMessage)));
return new JsonResult(new APIResponseModel<object> { Code = ResponseEnum.FAIL.GetHashCode(), Message = JsonConvert.SerializeObject(errors), Data = errors });
};
});
};
});
自定义验证
public class NoSpaceAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value is string str)
{
return !str.Contains(' ');
}
return false;
}
}