I'm building an API in C# with .NET Web API 2.2. I'm validating the request and returning an 'error' response via ModelState.
[ResponseType(typeof(IEnumerable<CustomerModel>))]
public IHttpActionResult Get([FromBody]List<CustomerSearchModel> row)
{
if (ModelState.IsValid)
{
CustomerLookupModel model = new CustomerLookupModel(row);
model.Init();
model.Load();
return Ok(model.Customers);
}
else
{
return BadRequest(ModelState);
}
}
Here is a sample 'error' response.
{
"message": "The request is invalid.",
"modelState": {
"row[0].Country": ["'Country' should not be empty."]
}
}
In the 'error' response, I would like to change the word 'modelState' to 'error'. I thought I could do that by copying the 'ModelState' object and naming it 'error'... and include that with BadRequest.
return BadRequest(error);
That didn't work. I must be missing something simple.
ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process.
IsValid is false now. That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.
Return anonymous object:
public HttpResponseMessage GetModelStateErrors()
{
//return Request.CreateResponse(HttpStatusCode.OK, new Product());
ModelState.AddModelError("EmployeeId", "Employee Id is required.");
ModelState.AddModelError("EmployeeId", "Employee Id should be integer");
ModelState.AddModelError("Address", "Address is required");
ModelState.AddModelError("Email", "Email is required");
ModelState.AddModelError("Email", "Invalid Email provided.");
var error = new {
message = "The request is invalid.",
error = ModelState.Values.SelectMany(e=> e.Errors.Select(er=>er.ErrorMessage))
};
return Request.CreateResponse(HttpStatusCode.BadRequest, error);
}
Fiddler output:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With