从任务<httpresponsemessage>获取HttpResponseMessage

时间:2016-07-28 10:26:48

标签: c# asp.net .net asp.net-web-api

在HttpClient内部使用语句我需​​要从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;
}

我的问题是:如何从此行获取HttpResponseMessage

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

2 个答案:

答案 0 :(得分:2)

你应该await任务:

HttpResponseMessage m = await client.GetAsync(url);   

为此,需要将调用方法标记为async

答案 1 :(得分:0)

要获取HttpResponseMessasge,应使用Task.Result属性。 这是您从Task获得的HttpResponseMessage的代码(经过一些修改):

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;
}