我有一个程序,它发出一个 Post 请求。这个项目运行得很好,但是对于旧版本的 .NETCORE
(1.1) ,我已经将包括框架在内的所有内容都升级到了 2.1
。从来没有更改过代码,没有发生错误,看起来更改没问题。
现在我的 Post 请求失败了(我只附上一个,但我有大约 4 个 Post 请求,它们都因同样的原因而失败)
编辑:我刚刚也测试了我的 Get 请求,产生了同样的错误..
这是我的代码:
using (var client = new HttpClient())
{
Field fld = new Field()
{
...
};
ForJSON bodyFormat = new ForJSON()
{
...
};
string output = JsonConvert.SerializeObject(bodyFormat);
StringContent sc = new StringContent(output, Encoding.UTF8, "application/json");
try
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
Encoding.ASCII.GetBytes(
string.Format("{0}:{1}", "XX", "YY"))));
response = await client.PostAsync("https:...", sc); // It fails here
错误信息是:
attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
我试过用谷歌搜索这个错误,但每篇文章似乎都与我无关。他们在谈论权限防火墙和端口,但为什么它在一个项目中有效而在另一个项目中却无效?
如果我尝试通过 Postman/我对 1.1 版本的项目进行备份,那么它就可以工作。
为什么会这样?什么坏了?我可能需要添加超时属性吗?
最佳答案
attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
这个错误是由于core 1.1和core 2.1的变化导致HttpClientHandler
由WinHttpHandler
变成了SocketsHttpHandler
。
对于解决方法,您可以尝试配置一个进程以使用旧的 HttpClientHandler
AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
using (var client = new HttpClient())
错误跟踪:.NET Core 2.1 SocketsHttpHandler proxy authentication using Windows auth is broken #30166
关于C# Post 请求被破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52150809/