Acumatica契约式REST API GET调用超时报错:A task was canceled.
我之前也碰到过类似的坑,结合你的代码和Acumatica REST API的特性,给你几个排查方向和解决方案:
可能的原因及修复方案
1. 未读取登录请求的响应内容,导致连接池阻塞
你的代码里,登录的PostAsync请求虽然用了using包裹响应对象,但完全没读取它的响应内容。HttpClient默认会复用连接,但如果响应体没被读取,连接可能不会被释放回连接池,后续的GetAsync请求就会一直等可用连接,最终超时抛出"A task was canceled."。
修改代码,先读取登录请求的响应内容(哪怕你用不上),确保连接被释放:
var str = new StringContent( JsonConvert.SerializeObject( new { name = "admin", password = "admin", company = "Company", branch = "" }), Encoding.UTF8, "application/json"); string baseUrl = "http://localhost/AcuAmazon172040019"; using (HttpClient client = new HttpClient()) { // 先处理登录请求,必须读取响应内容释放连接 using (HttpResponseMessage res = await client.PostAsync(baseUrl + "/entity/auth/login", str)) { // 强制检查登录是否成功,避免后续无意义请求 res.EnsureSuccessStatusCode(); // 读取响应内容,让HttpClient回收连接 var _ = await res.Content.ReadAsStringAsync(); } // 再执行Get请求 using (HttpResponseMessage res2 = await client.GetAsync(baseUrl + "/entity/Default/6.00.001/salesorder/so/001337")) { res2.EnsureSuccessStatusCode(); using (HttpContent content = res2.Content) { string data = await content.ReadAsStringAsync(); if (data != null) { Console.WriteLine(data); } } } }
2. HttpClient默认超时时间不够用
Acumatica查询复杂的销售订单时,处理时间可能会超过HttpClient默认的100秒超时。你可以手动设置更长的超时时间:
using (HttpClient client = new HttpClient()) { // 设置5分钟超时,根据实际需求调整 client.Timeout = TimeSpan.FromMinutes(5); // 后续登录、查询代码... }
3. 没确认登录请求是否真的成功
如果登录请求实际失败了(比如密码错误、公司名称拼写不对),后续的Get请求会因为未授权被服务器挂起,最终导致超时。一定要用res.EnsureSuccessStatusCode()检查登录响应,它会直接抛出异常帮你快速定位登录问题。
4. 手动维护Cookie容器(可选排查)
虽然HttpClient默认会自动维护Cookie,但你可以手动指定Cookie容器来确认会话是否正常传递:
var cookieContainer = new CookieContainer(); using (HttpClientHandler handler = new HttpClientHandler() { CookieContainer = cookieContainer }) using (HttpClient client = new HttpClient(handler)) { // 后续登录、查询代码... }
内容的提问来源于stack exchange,提问作者Tony Lanzer
相关产品推荐
相关产品推荐

