Blazor Server部署至Ubuntu服务器后无法调用Binance测试网接口
本地运行正常,发布到Ubuntu服务器后调用testnet.binance.vision接口报错,报错信息如下:
fail: Microsoft.AspNetCore.Components.Server.Circuits.CircuitHost[111]
Unhandled exception in circuit 'YT-5hUsabWHhqsnewYD0_YAdubDWkaPxkx144q2ZYN0'.
Binance.Common.BinanceClientException: Exception of type 'Binance.Common.BinanceClientException' was thrown.
at Binance.Common.BinanceService.SendAsync[T](String requestUri, HttpMethod httpMethod, Object content)
at Binance.Common.BinanceService.SendPublicAsync[T](String requestUri, HttpMethod httpMethod, Dictionary`2 query, Object content)
at Binance.Spot.Market.CurrentAveragePrice(String symbol)
at TORCHAIN.Components.CryptoTracker.PricesComponent.OnInitializedAsync() in A:\Users\sam_sepi0l\Desktop\PROJECTS\NEWFORUM\TORCHAIN\Components\CryptoTracker\PricesComponent.razor.cs:line 25
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)
报错发生在代码第25行:
var result = await market.CurrentAveragePrice(symbol);
接口调用相关代码:
private static HttpClient _httpClient = new HttpClient(); public List<string> Lista = new List<string>(); protected async override Task OnInitializedAsync() { #region BinanceAPI using (_httpClient = new HttpClient()) { _httpClient.BaseAddress = new Uri("https://testnet.binance.vision"); _httpClient.Timeout = new TimeSpan(0, 0, 5); _httpClient.DefaultRequestHeaders.Clear(); _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); _httpClient.DefaultRequestHeaders.Add("X-MBX-APIKEY", "APIKEY"); _httpClient.DefaultRequestHeaders.Add("SecretKey", "SECRETKEY"); var symbol = "BTCBUSD"; var market = new Market(_httpClient); var result = await market.CurrentAveragePrice(symbol); BinancePrice? Token = JsonConvert.DeserializeObject<BinancePrice>(result); Lista.Add(Token!.Price.ToString()); } #endregion }
更新疑问
怀疑是Linux环境代理配置导致问题,需要调整哪些配置解决?
针对Ubuntu环境下的代理及相关网络问题,按以下步骤排查和配置:
1. 系统全局代理排查与配置
- 查看当前系统是否设置全局代理:
echo $http_proxy echo $https_proxy - 若输出非空且服务器无需代理访问外网,清空代理:
unset http_proxy unset https_proxy - 若需保留代理但Binance接口无需走代理,添加例外:
export NO_PROXY="testnet.binance.vision,localhost,127.0.0.1" - 要让配置永久生效,编辑
~/.bashrc或/etc/profile文件,添加上述命令后执行source ~/.bashrc生效。
2. .NET应用层面代理控制
方式一:代码中强制禁用代理
修改HttpClient初始化逻辑,绕过系统代理:
using (_httpClient = new HttpClient(new HttpClientHandler { UseProxy = false })) { // 原有BaseAddress、请求头等配置... }
方式二:通过配置文件管理代理
在appsettings.json中添加代理规则:
{ "HttpClient": { "Proxy": { "Enabled": false, "BypassList": ["testnet.binance.vision"] } } }
若需要指定代理,配置如下:
{ "HttpClient": { "Proxy": { "Enabled": true, "Address": "http://your-proxy:port", "BypassOnLocal": true, "BypassList": ["testnet.binance.vision"] } } }
然后在Program.cs中读取配置并注入HttpClient:
builder.Services.AddHttpClient("BinanceClient", client => { client.BaseAddress = new Uri("https://testnet.binance.vision"); client.Timeout = TimeSpan.FromSeconds(5); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); client.DefaultRequestHeaders.Add("X-MBX-APIKEY", "APIKEY"); }).ConfigurePrimaryHttpMessageHandler(() => { var proxyConfig = builder.Configuration.GetSection("HttpClient:Proxy"); var handler = new HttpClientHandler(); if (proxyConfig.GetValue<bool>("Enabled")) { handler.Proxy = new WebProxy(proxyConfig["Address"]); handler.BypassProxyOnLocal = proxyConfig.GetValue<bool>("BypassOnLocal"); var bypassList = proxyConfig.GetSection("BypassList").Get<string[]>(); if (bypassList != null) { foreach (var host in bypassList) { handler.Proxy.BypassList.Add(host); } } } else { handler.UseProxy = false; } return handler; });
组件中注入使用命名HttpClient:
private readonly HttpClient _httpClient; public PricesComponent(IHttpClientFactory httpClientFactory) { _httpClient = httpClientFactory.CreateClient("BinanceClient"); }
3. 网络连通性与防火墙检查
- 测试服务器到Binance测试网的连通性:
curl -v https://testnet.binance.vision/api/v3/avgPrice?symbol=BTCBUSD - 若curl无法访问,开放出站HTTPS端口:
sudo ufw allow out 443/tcp - 若仍无法访问,检查服务器所在网络的安全组规则,确认已开放对
testnet.binance.vision的出站访问权限。
4. SSL证书问题修复
Linux环境可能缺少根证书导致HTTPS验证失败,安装并更新证书:
sudo apt-get update && sudo apt-get install ca-certificates -y sudo update-ca-certificates
内容的提问来源于stack exchange,提问作者Software Architect

