首页 文章

我应该尝试从我的API返回BadRequest(ModelState),并使用JSON.NET反序列化为* what *吗?

提问于
浏览
0

TL;DR;

“我喜欢生成的AutoRest客户端在处理200个场景时如何反序列化我的主要实体..但是,我必须手动解析400个场景吗?”,懒惰的程序员说

DETAILS:

所以,我有一个API,(Web API 2),我做所有标准的东西..使用POCO实现 IValidatable 除了使用 System.Data.DataAnnotations 属性级验证我的Web API返回400这样的错误(只是一个例子):

if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

并且,在适当的情况下,我使用 SwaggerResponse 属性,因此我的swagger.json被记录在案,以便我生成的客户端知道400是可行的响应 .

现在,我的单元测试直接实例化api控制器,我故意尝试测试无效模型状态 . 我可以从控制器调用中获取 IHttpActionResult 响应,并将其转换为 InvalidModelStateResult 并迭代ModelState字典 .

enter image description here

但是,我发现使用实际的HTTP客户端为我的“ 生产环境 HTTP调用”编写类似的内容 - 并不是那么简单 .

所以,更接近我的问题的核心:

Is there a preferred method for deserializing the InvalidModelStateResult?

所以,当我使用实际的http调用与我的API进行交互时...通过 Microsoft.Rest.ServiceClient 我得到的JSON的形状略有不同..

示例MVC控制器代码与我的API交互:

HttpOperationResponse resp = await client.SpecialLocations.PatchByIdWithHttpMessagesAsync(id, locationType, "return=representation");

if (!resp.Response.IsSuccessStatusCode)
{
    //The JSON returned here is not really in the form of an InvalidModelStateResult
    ViewBag.Error = await resp.Response.Content.ReadAsStringAsync();
    return View(locationType);
}

example of JSON when a 400 response is recieved

1 回答

  • 0

    所以,就目前而言,我需要解析从我的WebAPI返回的 ModelState (再次 - 它's not really named as such once retrieved via http request) and now pushing it into my MVC controller' s ModelState .

    这是我现在的答案 . 但是会考虑其他有 Value 的人 . 这似乎是一件奇怪的事情 .

    HttpOperationResponse resp = await client.SpecialLocations.PatchByIdWithHttpMessagesAsync(id, locationType, "return=representation");
    
    if (resp.Response.StatusCode == HttpStatusCode.BadRequest)
    {
      string jsonErrStr = await resp.Response.Content.ReadAsStringAsync();
      JObject err = JObject.Parse(jsonErrStr);
      string[] valPair = ((string)err["error"]["innererror"]["message"]).Split(":".ToCharArray());
    
      //now push into MVC controller's modelstate, so jQuery validation can show it
      this.ModelState.AddModelError(valPair[0].Trim(),valPair[1].Trim());
      return View(locationType);
    }
    

相关问题