我们正在向ResponseMessage.Content中持续返回[]的API发布“maintenanceEvent”。如果我在这里写的代码有问题,我需要一些专家指导。为什么ResponseMessage.Content在等待PostAsJsonAsync请求后一直为空?
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命令下面的代码中。但我不知道该怎么做。谢谢你的帮助。
是ResponseContent的真的类型任务?如果它是字符串类型,则需要等待该行中的ReadAsStringAsync()。 –
sellotape
感谢sellotape。如果我这样做,那么我怎样才能将结果分配给一个字符串?我正在阅读异步内容,并正在观看Stephen Taub的演示文稿。我只是试过这个,并得到了一个隐式的转换警告:var responseContentString = await this.responseInfo.ResponseMessage.Content.ReadAsStringAsync(); this.responseInfo.ResponseContent = responseContentString.ToString(); –
这不是一种类型的任务。所以我试过这个:任务 response =等待httpClient.PostAsJsonAsync(access.EndpointDirectory,stringContent).ConfigureAwait(false);现在Intellisense显示,“不能隐式地将类型'System.Net.Http.HttpResponseMessage'转换为'System.Threading.Tasks.Task '。 –