Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16280

Get content result from HttpRequestMessage?

I have the following code:

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;

The above request should return a string result, however, the result is empty. Would am I missing?

Upvotes: 1

Views: 3807

Answers (1)

Petter Hesselberg
Petter Hesselberg

Reputation: 5498

You can't use the result until after the continuation has run, so move the assignment to the Text property into the continuation:

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

An additional complication is that the Text property only wants to be set on the UI thread:

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

EDIT

Await/async is usually easier to work with; you can replace the above with this:

var message = await client.SendAsync(request);
responseResult = await message.Content.ReadAsStringAsync();
txtLog.Text = responseResult;

Upvotes: 2

Related Questions