拦截的WebAPI JSON格式错误 [英] Intercept webapi json formatting errors
本文介绍了拦截的WebAPI JSON格式错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望有一种方式来拦截,当你发送畸形的JSON到的WebAPI端点出现的异常,所以,相对于仅仅500(如修复我可以返回一个语义错误code你破碎的JSON或下地狱)
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")
推荐答案
您可以通过<一个派生创建自定义的验证筛选器属性href="http://msdn.microsoft.com/en-us/library/system.web.http.filters.actionfilterattribute(v=vs.118).aspx"相对=nofollow> ActionFilterAttribute
:
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()
或通过在全球范围注册它的配置
:
config.Filters.Add(new ValidationFilterAttribute());
这篇关于拦截的WebAPI JSON格式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文