.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)
{
...
}
-----------------------------------------
有時在會走之前你就得跑
你不解決問題 就等問題解決你