diff --git a/AssetManager.Infrastructure/Services/ExchangeRateService.cs b/AssetManager.Infrastructure/Services/ExchangeRateService.cs index 6134ca8..80d7f61 100644 --- a/AssetManager.Infrastructure/Services/ExchangeRateService.cs +++ b/AssetManager.Infrastructure/Services/ExchangeRateService.cs @@ -50,17 +50,17 @@ public class ExchangeRateService : IExchangeRateService try { - // 以USD为基础货币获取所有汇率 - var response = await _httpClient.GetFromJsonAsync($"https://v6.exchangerate-api.com/v6/4a8a42b4b9a3c4d5e6f7a8b9/latest/{BaseCurrency}"); + // 使用免费的开放汇率接口,无需API key + var response = await _httpClient.GetFromJsonAsync($"https://open.er-api.com/v6/latest/{BaseCurrency}"); - if (response == null || response.ConversionRates == null || response.Result != "success") + if (response == null || response.Rates == null || response.Result != "success") { _logger.LogError("汇率API调用失败: {Message}", response?.ErrorType ?? "未知错误"); throw new Exception("汇率服务暂时不可用"); } // 转换为USD -> 目标币种的汇率字典 - var usdRates = response.ConversionRates; + var usdRates = response.Rates; // 计算 from -> to 的汇率:(1 from = x USD) * (1 USD = y to) = x*y to decimal fromToUsd = 1 / usdRates[fromCurrency.ToUpper()]; @@ -125,7 +125,7 @@ public class ExchangeRateService : IExchangeRateService } /// -/// 汇率API响应模型 +/// 汇率API响应模型(exchangerate-api.com) /// public class ExchangeRateResponse { @@ -133,3 +133,13 @@ public class ExchangeRateResponse public string ErrorType { get; set; } = string.Empty; public Dictionary ConversionRates { get; set; } = new(); } + +/// +/// 开放汇率API响应模型(er-api.com) +/// +public class OpenExchangeRateResponse +{ + public string Result { get; set; } = string.Empty; + public string ErrorType { get; set; } = string.Empty; + public Dictionary Rates { get; set; } = new(); +}