我們正在向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 '。 –