Tej*_*tar 4 c# asynchronous httpclient async-await
我正在尝试在我的web api包装器中编写一个方法.我想使用"async/await"功能,以便UI不会被阻止.下面是web api包装器中的代码片段.
public static async Task Get<T>(Dictionary<string, string> paramDictionary, string controller)
{
try
{
string absoluteUrl = BaseUrl + controller + "?";
absoluteUrl = paramDictionary.Aggregate(absoluteUrl,
(current, keyValuePair) => current + (keyValuePair.Key + "=" + keyValuePair.Value + "&"));
absoluteUrl = absoluteUrl.TrimEnd('&');
using (HttpClient client = GetClient(absoluteUrl))
{
HttpResponseMessage response = await client.GetAsync(absoluteUrl);
return await response.Content.ReadAsAsync<T>();
}
}
catch (Exception exception)
{
throw exception;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我在下面的语句中遇到编译器错误.
HttpResponseMessage response = await client.GetAsync(absoluteUrl);
Run Code Online (Sandbox Code Playgroud)
它说"Type System.Threading.Tasks.Task <System.Net.Http.HttpResponseMessage> is not awaitable".经过多次搜索后,我无法摆脱这个错误.我出错的任何想法?请帮忙.
据我所知,这是因为你的方法返回Task,而不是Task<T>.所以你做不到return await response.Content.ReadAsAsync<T>().更改签名以返回Task<T>:
public static async Task<T> Get<T>(...)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8596 次 |
| 最近记录: |