1

I'm having issues dealing with a http error response from webapi when there are ModelState errors, namely the fact that 'ModelState' isn't a collection but properties so I can't loop through them.

I'm struggling to find any information on how others are dealing with this, it must be a common use case?

Controller

if (!ModelState.IsValid)
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);

Resulting JSON

{  
    "readyState":4,
    "responseText":"{\"Message\":\"The request is invalid.\",\"ModelState\":{\"model.Property1\":[\"'Property1' should not be empty.\"],\"model.Property2\":[\"'Property2' should not be empty.\"],\"model.Property3\":[\"'Property3' should not be empty.\"]}}",
    "responseJSON":{  
      "Message":"The request is invalid.",
      "ModelState":{  
         "model.Property1":[  
            "'Property1' should not be empty."
         ],
         "model.Property2":[  
            "'Property2' should not be empty."
         ],
         "model.Property3":[  
            "'Property3' should not be empty."
         ]
      }
    },
    "status":400,
    "statusText":"Bad Request"
}
0

1 Answer 1

1

In my case i'm using

HttpResponseMessage response = null;
if (!ModelState.IsValid)
            {
                response = request.CreateResponse(HttpStatusCode.BadRequest,
                    ModelState.Keys.SelectMany(k => ModelState[k].Errors)
                          .Select(m => m.ErrorMessage).ToArray());
            }

then return the response

Sign up to request clarification or add additional context in comments.

1 Comment

Ideally I would have liked to have kept using CreateErrorResponse and dealt with it in the client. However this is what I'm going to go with for now so I'll accept.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.