Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Web API - Error Response with ModelState

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.

like image 248
Bill Avatar asked Aug 27 '16 03:08

Bill


People also ask

What does ModelState IsValid mean?

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.

What causes false IsValid ModelState?

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.


1 Answers

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:

enter image description here

like image 68
Developer Avatar answered Oct 13 '22 04:10

Developer