问题描述
使用以下.Net Core 2.1控制台应用程序...
Given the following .Net Core 2.1 Console App...
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
namespace TestHttpClient
{
class Program
{
static void Main(string[] args)
{
try
{
using (var httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string url = "https://jsonplaceholder.typicode.com/posts/1";
var response = httpClient.GetAsync(url).Result;
string jsonResult = response.Content.ReadAsStringAsync().Result;
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
}
}
对GetAsync的调用挂起并引发异常,并显示以下消息:
The call to GetAsync hangs throwing an exception with the following message:
但是,切换到.Net Core 2.0,它可以正常工作...
注意
NOTE
我尝试使用:
HttpClientFactory -> Same result
WebRequest -> Same result
有什么想法吗?
UPDATE 1
此功能在不在公司网络上时有效,这可能意味着代理的行为发生了变化。但是,无论如何尝试找到区别,core2.0仍然有效。
UPDATE 1This works when not on the corporate network which might mean a change in behavior with the proxy perhaps. However, core2.0 still works regardless so trying to find the difference.
UPDATE 2
看起来像是引入了一个错误,并且据报道...
UPDATE 2Looks like a bug was introduced and it is reported...
推荐答案
显然,这是一个错误/重大变化的报告。
So apparently there is a bug/breaking change reported on this.
此处:
我认为这是我遇到的两个独立但相关的问题。
Two separate but related issues that I believe is what I am experiencing.
但是,我发现这似乎是一种解决方法。
However, I found what appears to be a workaround.
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace TestHttpClient
{
static class Program
{
static async Task Main(string[] args)
{
try
{
using (var httpClient = new HttpClient(new WinHttpHandler() { WindowsProxyUsePolicy = WindowsProxyUsePolicy.UseWinInetProxy }))
{
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string url = "https://jsonplaceholder.typicode.com/posts/1";
var response = await httpClient.GetAsync(url);
string jsonResult = await response.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
throw;
}
}
}
}
这里的关键部分是使用 WinHttpHandler
并将 WindowsProxyUsePolicy
设置为 WindowsProxyUsePolicy.UseWinInetProxy
The key part here is to use WinHttpHandler
and set the WindowsProxyUsePolicy
to WindowsProxyUsePolicy.UseWinInetProxy
WinHttpHandler
通过添加nuget包
WinHttpHandler
is found by adding nuget package System.Net.Http.WinHttpHandler
这篇关于带有.Net Core 2.1的HttpClient挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!