I'm implementing a REST API project using ASP.NET Core MVC 2.0, and I'd like to return a 400 status code if model binding failed (because the request is syntactically wrong) and a 422 status code if model validation failed (because the request is syntactically correct but contains unacceptable values).
As an example, given an action like
[HttpPut("{id}")]
public async Task<IActionResult> UpdateAsync(
[FromRoute] int id,
[FromBody] ThingModel model)
I'd like to return a 400 status code when the id
parameter in the route contains a non-digit character or when no body has been specified in the request and a 422 status code when the properties of ThingModel
contain invalid values.
From what I've seen both IValueProvider
and IModelBinder
implementations add their errors to the request's ModelStateDictionary
like the validators do, and there is no way to inject code between binding and validation.
How can I implement such a behavior?
Add attribute below in your project
Change your api like this
id
contains a non-digit => 400model
does not pass annotation validation inside => 400if you want to reject unacceptable values in model with
422
code, implement in your controller