首页 新闻 搜索 专区 学院

.net发送post请求时抛出这个异常,one or more errors occurred(A task was canceled)

0
悬赏园豆:50 [待解决问题]

代码如下所示:

protected string PostRequestAsync(string uri, dynamic payload, string ContentType = "application/json") 
        {
            var result = "";
            //处理Https
            var handler = new HttpClientHandler();
            handler.AllowAutoRedirect = true;
            System.Net.ServicePointManager.SecurityProtocol =  SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            handler.ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return true; };
            //构建请求
            using (var httpClient = new HttpClient(handler)) 
            {
                //20秒响应时间
                httpClient.Timeout = new TimeSpan(0, 0, 0, 20);
                HttpResponseMessage message = null;
                try
                {
                    //将请求payload序列化
                    var payloadString = JsonHelper.Serialize(payload);
                    HttpContent content = new StringContent(payloadString);
                    //httpClient.DefaultRequestHeaders.Add(HttpClientSession.TokenName, HttpClientSession.Token);
                    content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(ContentType);
                    var plateformPostUrl = HttpClientSession.PlateformUrl+uri;
                    var response =  httpClient.PostAsync(plateformPostUrl, content);
                    message = response.Result;
                    //如果返回码为200认为成功并返回结果
                    //如果Body内的code为500也认为成功,但要在业务中进行处理
                    if (message != null && message.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        result = message.Content.ReadAsStringAsync().Result;
                    }
                    else
                    {
                        throw new Exception($"code:{message.StatusCode},message:{message.Content.ReadAsStringAsync().Result}");
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
            return result;
        }

为什么会抛这个异常呀,这个方法是我在网上学到的

王ちゃん的主页 王ちゃん | 初学一级 | 园豆:152
提问于:2022-08-04 16:33
< >
分享
所有回答(4)
0

相应超时了吧

poorboss | 园豆:208 (菜鸟二级) | 2022-08-04 17:29
0

建议去掉 catch (Exception ex) 部分的代码可以看到更详细的错误信息

dudu | 园豆:36473 (高人七级) | 2022-08-05 09:14
0

用await 等待异步执行完成

diudiu1 | 园豆:726 (小虾三级) | 2022-08-05 09:37
0

(A task was canceled) 你设置了 超时时间 20秒没响应 httprequest 自动取消了。。

Постой! | 园豆:842 (小虾三级) | 2022-08-05 14:23

我很好奇。调了什么接口 20秒 没结果。。。

支持(0) 反对(0) Постой! | 园豆:842 (小虾三级) | 2022-08-05 14:25
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册