Intercept webapi json formatting errors

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

I'd like to have a way to intercept the exception that occurs when you send in malformed json to a webapi endpoint, so that I can return a semantic error code as opposed to just 500. (e.g. "Fix your broken JSON or go to hell")

回答1:

You can create your custom validation filter attribute by deriving from ActionFilterAttribute:

public class ValidationFilterAttribute : ActionFilterAttribute {     public override void OnActionExecuting(HttpActionContext actionContext)     {         if (!actionContext.ModelState.IsValid)         {             actionContext.Response = actionContext                                      .Request                                      .CreateErrorResponse(HttpStatusCode.BadRequest,                                                           actionContext.ModelState);         }     } } 

Now, you may either decorate your actions with it:

[HttpGet] [ValidationFilter()] public string DoSomethingCool() 

or register it globally via your config:

config.Filters.Add(new ValidationFilterAttribute()); 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!