Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/31.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在没有异步的情况下使用HttpClient_C#_Asp.net_Asp.net Mvc_Webclient - Fatal编程技术网

C# 如何在没有异步的情况下使用HttpClient

C# 如何在没有异步的情况下使用HttpClient,c#,asp.net,asp.net-mvc,webclient,C#,Asp.net,Asp.net Mvc,Webclient,你好,我是下面的 静态异步任务GetProductAsync(字符串路径) { Product=null; HttpResponseMessage response=wait client.GetAsync(路径); if(响应。IsSuccessStatusCode) { product=wait response.Content.ReadAsAsync(); } 退货产品; } 我在我的代码中使用了这个示例,我想知道是否有任何方法可以使用HttpClient,而不使用async/await

你好,我是下面的

静态异步任务GetProductAsync(字符串路径)
{
Product=null;
HttpResponseMessage response=wait client.GetAsync(路径);
if(响应。IsSuccessStatusCode)
{
product=wait response.Content.ReadAsAsync();
}
退货产品;
}
我在我的代码中使用了这个示例,我想知道是否有任何方法可以使用
HttpClient
,而不使用
async/await
,以及如何只获得字符串响应

提前感谢您

当然您可以:

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();
        }
    }
 }
但正如@MarcinJuraszek所说:

“这可能会导致ASP.NET和WinForms中的死锁。使用.Result或 .Wait()使用TPL时应小心”

下面是使用
WebClient.DownloadString

using (var client = new WebClient())
{
    string response = client.DownloadString(path);
    if (!string.IsNullOrEmpty(response))
    {
       ...
    }
}
有没有办法在没有async/await的情况下使用HttpClient?我怎样才能只得到响应字符串

HttpClient
是专门为异步使用而设计的


如果要同步下载字符串,请使用
WebClient.DownloadString

仅供参考:这可能会导致ASP.NET和WinForms中出现死锁。在TPL中使用
.Result
.Wait()
时应谨慎。有关死锁的信息,请参阅此部分:为什么不
WebClient.DownloadString
而不是扭曲
HttpClient
,以避免使用它?哈哈!我刚刚就此发表了评论。答案正确。谢谢,但我只是按照我在question@KumarJ.:遵循指南的一部分是了解需要更改的内容。
using (var client = new WebClient())
{
    string response = client.DownloadString(path);
    if (!string.IsNullOrEmpty(response))
    {
       ...
    }
}