问题
模型验证无效时,没有进入到接口里,而是直接报400 Bad Request,非常不友好。
环境
SDK:.Net Core 2.2.401
开发工具:VS2017
step 1 创建接口
1 2 3 4 5 6 7 8 9 10 11 |
/// <summary> /// 注册 /// </summary> /// <param name="input">request Body</param> [HttpPost] [AllowAnonymous] public object PostRegister([FromBody] InputUserRegister input) { var userService = GetService<IUserService>(); return userService.Register(input); } |
Step 2 创建模型
引用命名空间
1 |
using System.ComponentModel.DataAnnotations; |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class InputUserRegister { [Required(ErrorMessage = "请填写用户名")] [StringLength(20, ErrorMessage = "用户名长度过长")] public string UserName { get; set; } [Required(ErrorMessage = "请填写密码")] [StringLength(20, ErrorMessage = "密码长度过长")] public string Password { get; set; } [Required(ErrorMessage = "请填写确认密码")] [Compare("Password", ErrorMessage = "两次输入的密码不一致")] public string ConfirmPassword { get; set; } } |
Step 3 测试
解决
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#region 禁止默认行为 services.Configure<ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = (context) => { if (context.ModelState.IsValid) return null; var error = ""; foreach (var item in context.ModelState) { var state = item.Value; var message = state.Errors.FirstOrDefault(p => !string.IsNullOrWhiteSpace(p.ErrorMessage))?.ErrorMessage; if (string.IsNullOrWhiteSpace(message)) { message = state.Errors.FirstOrDefault(o => o.Exception != null)?.Exception.Message; } if (string.IsNullOrWhiteSpace(message)) continue; error = message; break; } return new JsonResult(new Models.VModels.ErrorResponse(error.ToString())); }; }); #endregion |