user1765862
user1765862

Reputation: 14165

getting HttpResponseMessage from a Task<HttpResponseMessage>

Inside HttpClient using statement I need to unwrap from somewhere HttpResponseMessage.

using (HttpClient client = new HttpClient())
{
     client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authUser);
     Task<HttpResponseMessage> m = client.GetAsync(url);   
     // HttpResponseMessage msg = ???              
     task.Wait();
     return task.Result;
}

my question is: how can I get HttpResponseMessage from this line

Task<HttpResponseMessage> m = client.GetAsync(url);   

Upvotes: 2

Views: 3058

Answers (2)

Josip
Josip

Reputation: 75

To get HttpResponseMessasge you should use Task.Result property. Here is your code (a bit modified) with HttpResponseMessage got from Task:

using (HttpClient client = new HttpClient())
{
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authUser);
    Task<HttpResponseMessage> task = client.GetAsync(uri);
    **HttpResponseMessage msg = task.Result;**
    task.Wait();
    return task.Result;
}

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 157048

You should await the task:

HttpResponseMessage m = await client.GetAsync(url);   

In order to do that, the calling method needs to be marked async.

Upvotes: 2

Related Questions