【问题标题】:Retrieving Response Body from HTTP POST从 HTTP POST 检索响应正文
【发布时间】:2018-01-16 14:55:12
【问题描述】:

我正在发布到返回 409 响应代码的 API 以及如下所示的响应正文:

    { 
       "message": "Exception thrown.",
       "errorDescription": "Object does not exist"
    }

如何提取响应体并反序列化它?

我正在使用 HttpClient:

    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:60129");

    var model = new Inspection
    {
        CategoryId = 1,
        InspectionId = 0,
        Descriptor1 = "test descriptor 121212",
        Name = "my inspection 1121212"
    };

    var serializer = new JavaScriptSerializer();
    var json = serializer.Serialize(model);
    var stringContent = new StringContent(json, Encoding.UTF8, "application/json");

    var result = client.PostAsync("api/Inspections/UpdateInspection", stringContent);

    var r = result.Result;

我似乎是一件很平常的事情,但我很难找到数据在我的结果中的位置。

【问题讨论】:

    标签: c# asp.net-web-api http-post


    【解决方案1】:

    您可以对具体类型的响应内容使用ReadAsAsync<T>ReadAsStringAsync 来获取原始JSON 字符串。

    还建议使用 Json.Net 来处理 JSON。

    var response = await client.PostAsync("api/Inspections/UpdateInspection", stringContent);
    
    var json = await response.Content.ReadAsStringAsync();
    

    可以创建一个具体的响应模型

    public class ErrorBody { 
       public string message { get; set; }
       public string errorDescription { get; set; }
    }
    

    用于读取不成功的响应。

    var response = await client.PostAsync("api/Inspections/UpdateInspection", stringContent);
    
    if(response.IsSuccessStatusCode) {
        //...
    } else {
        var error = await response.Content.ReadAsAsync<ErrorBody>();
    
        //...do something with error.
    }
    

    【讨论】:

    • 就这么简单,非常感谢。我的问题是我在 Visual Studio 的本地窗口中查看响应对象,只是没有看到数据。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    • 1970-01-01
    相关资源
    最近更新 更多