.Net Core WebApi 模型验证无效时报400
作者:互联网
问题
模型验证无效时,没有进入到接口里,而是直接报400 Bad Request,非常不友好。
环境
SDK:.Net Core 2.2.401
开发工具:VS2017
step 1 创建接口
/// <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 创建模型
引用命名空间
using System.ComponentModel.DataAnnotations;
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 测试
解决
#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
标签:WebApi,Core,return,string,ErrorMessage,400,var,message,public 来源: https://www.cnblogs.com/EminemJK/p/11498852.html