Search code examples
asp.net-web-apiwebapp2

Return a list of error messages with 400 Bad Request response in Web API 2


How can I return a list of error messages from Web Api 2 with 400 Bad Request status code? See the example below. Usually I use BadRequest method to return the 400 status code but it doesn't have any overload where it accepts a collection of string. It has an overload where it accepts ModelStateDisctionary. Does it mean I will have to create ModelStateDictionary from a list of error messages?

[Route("")]
[HttpPost]
public IHttpActionResult Add(Object data)
{
    var valid = _serviceLayer.Validate(data);
    if(!valid) 
    {
        var errors = valid.Errors;
        // errors is an array of string 
        // How do I return errors with Bad Request status code here? 
    }
    var updatedObject = _serviceLayer.Save(data);
    return Ok(updatedObject);
}

Solution

  • As per Mike's comment, I am going to add a new class implementing IHttpActionResult to return a list of error messages with 400 Bad Request. Thanks Mark