Windows Server 2019上ASP.NET Core Web API调用Telegram Bot API超时问题
问题描述
- 现有一个ASP.NET Core Web API,用户创建内容时会调用Telegram Bot API发送消息到Telegram群组,此前正常运行1年半,近期在Windows Server环境下请求持续超时失败。
- 该API复制到本地IIS运行时一切正常。
- 搭建两个测试应用排查:一个使用相同的Telegram Bot NuGet包,另一个通过
IHttpClientFactory直接调用Telegram API,均出现超时,但调用其他第三方Web API正常。
相关代码
public async Task SendAsync(long receiver, Notification notification) { try { var response = await _bot.SendTextMessageAsync(new ChatId(receiver), text:notification.Body, parseMode:ParseMode.Html); if (response != null) return; throw new Exception($"Telegram Send Failed"); } catch (Exception e) { _logger.LogError(e.Message); } }
异常信息
An unhandled exception has occurred while executing the request.
Exception: Telegram.Bot.Exceptions.RequestException: Request timed out
System.Threading.Tasks.TaskCanceledException: The request was canceled due to the configured HttpClient.Timeout of 100 seconds elapsing.
System.TimeoutException: A task was canceled.
System.Threading.Tasks.TaskCanceledException: A task was canceled.
排查与解决建议
检查服务器网络连通性
- 在Windows Server上用
curl或PowerShell的Invoke-WebRequest直接调用Telegram Bot API(示例:https://api.telegram.org/bot<你的BotToken>/sendMessage?chat_id=<群组ID>&text=测试),确认是否能正常返回结果。若直接调用也超时,说明是服务器网络层面问题。 - 检查服务器防火墙是否封禁了Telegram API的域名/IP段,或出站规则限制了HTTPS请求到特定地址。
- 验证服务器DNS配置,可临时切换到公共DNS(如8.8.8.8)后重新测试。
- 在Windows Server上用
配置代理(若服务器需代理访问外网)
- 在
Program.cs中为HttpClient添加代理配置:builder.Services.AddHttpClient("TelegramClient") .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { Proxy = new WebProxy("http://你的代理地址:端口"), UseProxy = true }); - 确认代理服务器可正常访问Telegram API,且无IP限制或认证问题。
- 在
调整超时与重试策略
- 临时调高超时时间,并添加重试逻辑应对网络波动:
builder.Services.AddHttpClient<ITelegramBotClient>(client => { client.BaseAddress = new Uri("https://api.telegram.org/"); client.Timeout = TimeSpan.FromMinutes(2); }) .AddPolicyHandler(Policy.Handle<TaskCanceledException>() .Or<HttpRequestException>() .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt))));
- 临时调高超时时间,并添加重试逻辑应对网络波动:
验证Telegram Bot权限与状态
- 在服务器上访问
https://api.telegram.org/bot<你的BotToken>/getMe,确认Bot Token有效且未被封禁。 - 检查目标Telegram群组权限,确保Bot未被踢出且拥有发送消息的权限。
- 在服务器上访问
检查服务器TLS版本
- Telegram API要求使用TLS 1.2及以上版本,确认Windows Server已启用TLS 1.2/1.3,禁用过时的TLS 1.0/1.1(可通过注册表或IIS管理器配置)。
内容的提问来源于stack exchange,提问作者Sophart
相关产品推荐
相关产品推荐

