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 wron
Haven't checked option #1 yet, but:
Quick notes for the ApiBehaviorOptions:
So in some cases a custom filter is a better solution (less changes).
Add attribute below in your project
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
base.OnActionExecuting(context);
if (!context.ModelState.IsValid)
context.Result = new BadRequestObjectResult(new
{
message = context.ModelState.Values.SelectMany(v => v.Errors.Select(e => e.ErrorMessage))
});
}
}
Change your api like this
[HttpPut("{id}")]
[ValidateModel]
public async Task<IActionResult> UpdateAsync(
[FromRoute] int id,
[FromBody] ThingModel model)
id
contains a non-digit => 400
model
does not pass annotation validation inside => 400
if you want to reject unacceptable values in model with 422
code, implement in your controller