【问题标题】:Handling WebApi Error HttpResponseMessage client side处理 WebApi 错误 HttpResponseMessage 客户端
【发布时间】:2017-05-10 19:02:36
【问题描述】:

当出现 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"
}

【问题讨论】:

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


    【解决方案1】:

    就我而言,我正在使用

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

    然后返回响应

    【讨论】:

    • 理想情况下,我希望继续使用 CreateErrorResponse 并在客户端处理它。不过,这就是我现在要做的,所以我会接受。
    猜你喜欢
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2019-06-09
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多