2016-05-25 5 views
1

私は次のコードを持っている:HttpRequestMessageからコンテンツの結果を取得しますか?

var client = new HttpClient() 
{ 
    BaseAddress = new Uri(@"https://myhost:myport/"), 
}; 
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

var uri = @"myurl"; 

var s = JsonConvert.SerializeObject(myobject); 
string responseResult = string.Empty; 

HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, uri); 
request.Content = new StringContent(s, Encoding.UTF8, "application/json"); 

client.SendAsync(request) 
     .ContinueWith(responseTask => 
     { 
      responseResult = responseTask.Result.Content.ReadAsStringAsync().Result; 
     }); 

txtLog.Text = responseResult; 

上記の要求は、文字列の結果を返す必要がありますが、しかし、結果は空です。私は行方不明ですか?

+1

ContinueWithは、そのメソッドがAsyncCallの後に実行されることを保証しますが、それでも非同期です。つまり、 "ContinueWith"が実行される前に "txtLog.Text"への割り当てが行われる可能性があります。 – Nicolas

答えて

1

あなたは継続が実行されるまでの結果を使用し、その継続にTextプロパティに割り当てを移動することはできません。

client.SendAsync(request) 
     .ContinueWith(responseTask => 
     { 
      responseResult = responseTask.Result.Content.ReadAsStringAsync().Result; 
      txtLog.Text = responseResult; 
     }); 

追加の複雑さがTextプロパティのみを設定することを望んでいることですUIスレッド上:

client.SendAsync(request) 
     .ContinueWith(responseTask => 
     { 
      responseResult = responseTask.Result.Content.ReadAsStringAsync().Result; 
      Dispatcher.Invoke(() => txtLog.Text = responseResult); 
     }); 

EDIT

通常、Await/asyncを使用する方が簡単です。

var message = await client.SendAsync(request); 
responseResult = await message.Content.ReadAsStringAsync(); 
txtLog.Text = responseResult; 
関連する問題