为什么在等待PostAsJsonAsync请求后,ResponseMessage.Content一直为空?

时间:2016-10-20 14:11:22

标签: c# asynchronous async-await

我们正在发布" maintenanceEvent"到一个在ResponseMessage.Content中始终返回[]的API。如果我在这里写的代码有问题,我需要一些专家指导。

private async Task SendMaintenanceEvent(object maintenanceEvent, MaintenanceEventType maintenanceEventType)
{
    string endpointAddress = "TheEndpointURI";
    string credentials = "OurCredentials";
    string credentialsBase64 = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(credentials));

    // Convert the maintenanceEvent object to consumable JSON, then encode it to a StringContent object.
    this.responseInfo.MaintenanceEventAsJSON = System.Web.Helpers.Json.Encode(maintenanceEvent);
    StringContent stringContent = new StringContent(this.responseInfo.MaintenanceEventAsJSON, Encoding.UTF8, "application/json");
    using (HttpClient httpClient = new HttpClient())
    {
        httpClient.BaseAddress = new Uri(endpointAddress);
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentialsBase64);
        this.responseInfo.AuthorizationHeader = httpClient.DefaultRequestHeaders.Authorization.ToString();
        this.responseInfo.EndpointUri = httpClient.BaseAddress.AbsoluteUri;

        // The async post.
        this.responseInfo.ResponseMessage = await httpClient.PostAsJsonAsync(access.EndpointDirectory, stringContent).ConfigureAwait(false);

        this.responseInfo.ResponseStatusCode = (int)this.responseInfo.ResponseMessage.StatusCode;

        // Consistently returns true so long as my credentials are valid.
        // When the auth credentials are invalid, this returns false.
        if (this.responseInfo.ResponseMessage.IsSuccessStatusCode)
        {
            // I expect to see some data from the service.
            this.responseInfo.ResponseContent = this.responseInfo.ResponseMessage.Content.ReadAsStringAsync();
        }
    }
}

尝试/捕获块,省略了一些公司特定信息。上面的responseInfo对象只是一个模型,它有一些属性可以从这个方法中收集信息,所以我们可以记录这个事件。

我怀疑可能存在问题,在PostAsJsonAsync命令下面的代码中。但我不知道该怎么做。谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

This (slightly adjusted) is what you want to do (substitute your own variables as needed):

using (HttpClient httpClient = new HttpClient())
{
    // ...
    HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(access.EndpointDirectory, stringContent).ConfigureAwait(false);
    // ...
    string responseBody = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
    // ...
}

I.e. you must await ReadAsStringAsync() to get the actual content.

For completeness, note that HttpResponseMessage and HttpResponseMessage.Content are IDisposable.