【问题标题】:How can I capture the HttpResponseMessage.Content after a PostAsJsonAsync for our records?如何在 PostAsJsonAsync 之后捕获 HttpResponseMessage.Content 以供我们记录?
【发布时间】:2016-10-18 18:20:25
【问题描述】:

我们将 JSON 发布到一项服务,该服务会在我们的网站发生更改时记录操作。发布 JSON 后,我们想从响应消息中捕获内容以记录它。

在 Visual Studio 监视窗格中,我可以看到内容,在发布后看起来像这样:

Id = 4,状态 = RanToCompletion,方法 =“{null}”,结果 =“[]”

上面的结果出现在watch中这条语句之后:

httpResponseMessage.Content.ReadAsStringAsync(), 交流

但每当我尝试将响应内容分配给字符串时,字符串值只是“[]”,而不是我希望在上面看到的属性列表(ID、状态等)。

这是一段简化的代码(try/catch 和其他部分省略)。在 PostAsJsonAsync 之后,我们得到一个 200 成功状态码。

public HttpResponseMessage httpResponseMessage { get; set; }
public string httpResponseMessageContent { get; set; }

private async Task SendMaintenanceEvent(object maintenanceEvent)
{
    string endpointAddress = "http://whereever";
    string targetDirectory = "OurTarget";
    string credentials = "Omitted";
    string credentialsBase64 = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(credentials));
    string maintenanceEventAsJSON = System.Web.Helpers.Json.Encode(maintenanceEvent);
    StringContent stringContent = new StringContent(maintenanceEventAsJSON, Encoding.UTF8, "application/json");

    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.BaseAddress = new Uri(endpointAddress);
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentialsBase64);
        this.httpResponseMessage = await httpClient.PostAsJsonAsync(targetDirectory, stringContent).ConfigureAwait(false);
        if (httpResponseMessage.IsSuccessStatusCode)
        {
            // Current value: "[]"
            // Expected value: Id = 4, Status = RanToCompletion, Method = "{null}", Result = "[]"
            this.httpResponseMessageContent = await httpResponseMessage.Content.ReadAsStringAsync();
        }
        else
        {
            throw new System.Exception("Error sending maintenance event.");
        }
    }
}

感谢您的帮助。

【问题讨论】:

  • 响应消息的内容似乎是“[]”,如结果变量所示。如果您想要 ID、Status 等,这些都是 httpResponseMessage 的直接子代,就像 Content 一样。当您从 Web 服务创建响应时,除了要包含的任何(可选)内容之外,您还添加了其他一些内容。尝试将整个 httpResponseMessage 捕获为变量,并使用辅助方法将您想要的属性解析为字符串。
  • 感谢元素皮特。这些属性没有出现在 httpResponseMessage 中。但是,这返回了我的预期。显着的区别是我删除了等待: var content = httpResponseMessage.Content.ReadAsStringAsync();正如你所说,看起来我需要解析这些。

标签: c# json asynchronous


【解决方案1】:

Id = 4, Status = RanToCompletion, Method = "{null}", Result = "[]" 是已完成异步Task 的调试视图,而不是 POST 的结果。 POST 的实际结果只是 Task.Result 属性(或使用 await 关键字获取)。 POST 的结果实际上只是 [] 一个空的 JSON 数组。你的客户端代码没问题,检查服务器。

【讨论】:

  • 尝试更改并调试:var task = httpResponseMessage.Content.ReadAsStringAsync(); string r = await task;
猜你喜欢
  • 1970-01-01
  • 2010-09-10
  • 1970-01-01
  • 2010-09-18
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多