How to discern between model binding errors and model validation errors?

后端 未结 2 1292
傲寒
傲寒 2020-12-19 17:01

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

2条回答
  •  佛祖请我去吃肉
    2020-12-19 17:45

    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 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

提交回复
热议问题