C# Post 请求被破坏

标签 c# web-services post asp.net-core

我有一个程序,它发出一个 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的变化导致HttpClientHandlerWinHttpHandler变成了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

关于C# Post 请求被破坏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52150809/

相关文章:

c# - MS VC++ 运行时库错误运行托管 C# 应用程序

c# - 我的代码有什么问题吗? (C# Winforms)

java - Soap 客户端抛出意外的元素异常

php - HTTP Post 到 MySQL 插入空白行

c# - 在编译时确保互斥接口(interface)?

c# - 是否可以将非主键设置为另一个表中的外键?

web-services - 使用 cURL 将 SAP 连接到远程 Web 服务

java - 在 JAX-RS 中的每个 @POST 或 @DELETE 请求之前或之后调用方法

jquery - 如何防止这个 jQuery 函数在每次页面加载时执行?

post - 如何使用带有 hyper 的 multipart/form-data 发布图像?