.NET Core API endpoint model validation

Example of simple method in an API controller for showing invalid posted model state.

[HttpPost("create")]
public ActionResult<MyModel> Create([FromBody] MyModel model)
{
    ValidateIncomingModel();
    return myBusiness.Create(model);
}

private void ValidateIncomingModel()
{
    if (!ControllerContext.ModelState.IsValid)
    {
        var errors = ControllerContext.ModelState.Keys
              .SelectMany(key => ControllerContext.ModelState[key].Errors
              .Select(x => key + ": " + x.ErrorMessage));
        var message = string.Join("\n", errors);
        throw new Exception($"Not valid incoming model\n {message}");
    }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *