C#帖子请求被破坏了

我有一个程序,它发出一个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

对于此错误,它是由核心1.1和核心2.1之间的更改引起的,HttpClientHandler从WinHttpHandler更改为SocketsHttpHandler.

对于变通方法,您可以尝试配置进程以使用较旧的HttpClientHandler

AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", false);
using (var client = new HttpClient())

参考:Networking Performance.

错误跟踪:.NET Core 2.1 SocketsHttpHandler proxy authentication using Windows auth is broken #30166

点赞