为什么是ResponseMessage ?在await PostAsJsonAsync请求后,内容始终为空
本文关键字:请求 ResponseMessage PostAsJsonAsync await 为什么 | 更新日期: 2023-09-27 18:14:13
我们正在向API发布一个"maintenanceEvent",该API在ResponseMessage.Content中始终返回[]。如果我在这里写的代码有问题,我需要一些专家的指导。
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();
}
}
}
Try/Catch块和一些公司特定信息被省略。上面的responseInfo对象只是一个带有一些属性的模型,用于从该方法收集信息,因此我们可以记录事件。
我怀疑问题可能在哪里,是在PostAsJsonAsync命令下面的代码。但我不知道该在那里做什么。谢谢你的帮助。
这就是您想要做的(根据需要替换您自己的变量):
using (HttpClient httpClient = new HttpClient())
{
// ...
HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(access.EndpointDirectory, stringContent).ConfigureAwait(false);
// ...
string responseBody = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
// ...
}
。您必须等待ReadAsStringAsync()
才能获得实际内容。
为完整起见,请注意HttpResponseMessage
和HttpResponseMessage.Content
为IDisposable