【问题标题】:Why do I not get the JSON body in the log?为什么我在日志中没有得到 JSON 正文?
【发布时间】:2018-10-05 16:42:42
【问题描述】:

我正在使用 HTTPClient 将 JSON 对象发送到 REST Web 服务,我正在捕获响应,但我只获取日志中的标头,而不是响应正文中的 JSON 响应。

相关代码如下

 HttpClient httpClient = new HttpClient();

 HttpResponseMessage response = await httpClient.PostAsync("https://example.com/api/checkout", new StringContent(transaction.ToString(), System.Text.Encoding.UTF8, "application/json"));

log.Info("response is " + response);

如何从响应中的正文捕获 JSON 响应?

【问题讨论】:

  • 通过从响应对象中读取(例如await response.Content.ReadAsStringAsync())?

标签: c# json


【解决方案1】:

你需要从内容流中读取正文

var json = await response.Content.ReadAsStringAsync();

【讨论】:

  • 有没有办法直接读入JObject?我需要得到它是字符串然后序列化它?
  • @MattDouhan 为什么像JObject.Parse(await response.Content.ReadAsStringAsync()) 这样的东西会给你带来麻烦?
  • @MattDouhan 1st HttpResponseMessage 不是string。第二次阅读string,然后将您的string 解析为和JObject,就像柯克·拉金所说的那样
【解决方案2】:

Response 是返回的对象,包含多个属性,例如 headers 或 httpcontext。

您需要将 content 属性读取为所需的类型,例如:

var jsonObj = await response.Content.ReadAsStringAsync();

您也可以跳过 ReadAsStringAsync() 并直接使用:

response.content.ReasAsSync<object>();

【讨论】:

    猜你喜欢
    • 2017-06-30
    • 2013-08-19
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2020-11-19
    相关资源
    最近更新 更多