从HTTP POST检索响应主体

时间:2018-01-16 14:55:12

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

我正在发布返回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;

我似乎很常见,但我很难找到数据在我的结果中的位置。

1 个答案:

答案 0 :(得分:3)

您可以对具体类型或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.
}