处理WebApi错误HttpResponseMessage客户端

时间:2017-05-10 10:55:16

标签: json asp.net-mvc asp.net-web-api

当存在ModelState错误时,我遇到了处理来自webapi的http错误响应的问题,即'ModelState'不是集合但属性因此我无法循环它们。

我很难找到其他人如何处理这个问题的任何信息,它必须是一个常见的用例?

控制器

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

产生的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"
}

1 个答案:

答案 0 :(得分:1)

就我而言,我正在使用

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

然后返回响应