Intercept webapi json formatting errors

非 Y 不嫁゛ 提交于 2020-01-01 18:50:06

问题


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());


来源:https://stackoverflow.com/questions/26424404/intercept-webapi-json-formatting-errors

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