[.NET Web API2] 要如何在ModelBinding falied送出我想要的错误讯息格式
.NET VERSION : .ner framework 4.6.1 WEB API 2
如果我需要在ModelState.isValid == false时, 送给前端特殊格式应该怎么做?
这里假设我需要传送给前端的错误讯息是"|object.property: xxx为必填|object.property:XXX格式不正确"的时候
应该要怎么写我的Filter呢?
public class ValidateModelFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { if (actionContext.ModelState.IsValid == false) { var sbError = new StringBuilder(128); foreach (var model in actionContext.ModelState) { var message = model.Value.Errors.FirstOrDefault().ErrorMessage; message = (string.IsNullOrEmpty(message)) ? model.Value.Errors.FirstOrDefault().Exception.Message : message; sbError.Append($"|{model.Key}:{message}"); } actionContext.Response = actionContext.Request.CreateErrorResponse( HttpStatusCode.BadRequest, sbError.ToString()); } } }
[ValidateModelFilter] public IHttpActionResult Post(LoginModel login) { ... }
posted on 2020-08-31 17:00 www.blender-3d.cn 阅读(87) 评论(0) 编辑 收藏 举报