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