Trying to return a correct error message instead of the WebAPI default one {"Message":"The request is invalid.","ModelState"
when Json deserialzation fails.
I implemented my custom ActionFilterAttribute:
internal class ValidateModelAttribute : ActionFilterAttribute {
public override void OnActionExecuting(HttpActionContext actionContext) {
if (!actionContext.ModelState.IsValid) {
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
}
I decorated my Controller method with this attribute:
[ValidateModelAttribute]
public async Task<HttpResponseMessage> Put(string username, string serviceId, [FromBody] Dictionary<string, string> jsonData)
{
// code
}
If I set a breakpoint in the OnActionExecuting
it only breaks when the jsonData
is parsed succesfully as a json. If the json is invalid it never gets into the filter, and the same error message is returned. So looks like this is done somewhere before but all the posts I found say that this should be the place to handle this.
Any idea what's wrong?