Kum*_* J. 7 c# asp.net asp.net-mvc webclient
您好我正在关注本指南
static async Task<Product> GetProductAsync(string path)
{
Product product = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
product = await response.Content.ReadAsAsync<Product>();
}
return product;
}
Run Code Online (Sandbox Code Playgroud)
我用这个例子在我的代码,我想知道有没有办法使用HttpClient没有async/await,我怎么能得到的唯一反应的字符串?
先感谢您
Ste*_*ary 20
有没有办法在没有async/await的情况下使用HttpClient,我怎样才能得到只有响应的字符串?
HttpClient 是专为异步使用而设计的.
如果要同步下载字符串,请使用WebClient.DownloadString.
Rom*_*syk 15
当然可以:
public static string Method(string path)
{
using (var client = new HttpClient())
{
var response = client.GetAsync(path).GetAwaiter().GetResult();
if (response.IsSuccessStatusCode)
{
var responseContent = response.Content;
return responseContent.ReadAsStringAsync().GetAwaiter().GetResult();
}
}
}
Run Code Online (Sandbox Code Playgroud)
但正如@MarcinJuraszek 所说:
“这可能会导致 ASP.NET 和 WinForms 中出现死锁。应谨慎使用 .Result 或 .Wait() 与 TPL”。
这是一个例子WebClient.DownloadString
using (var client = new WebClient())
{
string response = client.DownloadString(path);
if (!string.IsNullOrEmpty(response))
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12644 次 |
| 最近记录: |