2015-04-30 50 views
7

我正在使用HttpResponseMessage類作爲從服務返回JSON數據的AJAX調用的響應。當AJAX調用從服務返回後暫停執行時,我看到這個類包含一個類型爲System.Net.Http.StreamContent的Content屬性。如何將HttpResponseMessage內容讀取爲文本

如果我在瀏覽器中檢查,我看到網絡調用成功,JSON數據作爲響應。我只是想知道爲什麼我無法在Visual Studio中看到返回的JSON文本?我搜索了整個這個System.Net.Http.StreamContent對象,並沒有看到任何數據。

public async Task<HttpResponseMessage> Send(HttpRequestMessage request) { 
    var response = await this.HttpClient.SendAsync(request); 
    return response; 
} 
+1

也許你想向我們展示你的代碼? –

+0

對不起。 – PythonIsGreat

+1

你想要做什麼?檢查'response'變量? –

回答

23

響應的文本表示隱藏在HttpResponseMessage類的Content屬性。具體來說,你會得到這樣的回答:

response.Content.ReadAsStringAsync();

所有現代異步方法,比如,ReadAsStringAsync返回Task。要直接得到結果,使用任務的Result屬性:

response.Content.ReadAsStringAsync().Result;

注意Result阻止。您也可以awaitReadAsStringAsync()

+3

這將返回一個'任務'。您需要「等待」才能看到實際的字符串結果。 –

5

您可以在Content上使用ReadAsStringAsync。你通常應該使用await

var response = await client.SendAsync(request); 
var content = await response.Content.ReadAsStringAsync(); 

注 - 不.Result