You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现货币转换?谷歌API相关代码返回空值或403错误求助

解决C#中USD转INR货币转换的问题

Hey there! Let's break down why your existing code isn't working and walk through a reliable way to implement USD to INR currency conversion in C#.

为什么你的三段代码都失效了?

Let's go through each issue one by one:

  • 第一段代码返回null: The old Google calculator API (google.com/ig/calculator) was retired years ago. The response structure no longer matches your regex pattern, so your code can't capture any value—resulting in null.
  • 第二段代码出现403禁止访问: Google Finance has strict anti-scraping measures now. When you send a request without a proper User-Agent header (making it look like a bot), Google blocks your request with a 403 error.
  • 第三段代码仍有问题: Google's finance converter page has completely changed its HTML structure and enforces anti-scraping rules. Your string-splitting logic relies on outdated HTML elements that no longer exist, so it can't extract the conversion value correctly.

正确的实现方案

Instead of relying on deprecated or anti-scraped Google services, use a stable, free public currency API. Most of these services offer free tiers for limited requests, and they return structured JSON which is easy to parse. We'll use HttpClient (the modern replacement for WebClient/WebRequest) for better performance and reliability.

Step 1: Define a model to parse API responses

First, create a class to map the JSON response from your chosen API (adjust fields to match the API's response structure):

public class CurrencyConversionResult
{
    public bool Success { get; set; }
    public decimal ConversionRate { get; set; }
    public decimal ConversionResult { get; set; }
}

Step 2: Implement the conversion method

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Globalization;

public class CurrencyConverter
{
    // Reuse a single HttpClient instance to avoid socket exhaustion
    private static readonly HttpClient _httpClient = new HttpClient();

    static CurrencyConverter()
    {
        // Set a valid User-Agent to mimic a real browser and avoid blocks
        _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36");
    }

    public async Task<decimal> ConvertAsync(decimal amount, string fromCurrency, string toCurrency)
    {
        try
        {
            // Replace this with the actual endpoint of your chosen free currency API
            // Most free APIs require a free API key (sign up to get one)
            string apiUrl = $"https://api.your-service.com/convert?from={fromCurrency.ToUpper()}&to={toCurrency.ToUpper()}&amount={amount.ToString(CultureInfo.InvariantCulture)}&apikey=YOUR_FREE_API_KEY";
            
            HttpResponseMessage response = await _httpClient.GetAsync(apiUrl);
            response.EnsureSuccessStatusCode(); // Throw error if HTTP request fails

            var conversionData = await response.Content.ReadAsAsync<CurrencyConversionResult>();
            
            if (!conversionData.Success)
            {
                throw new InvalidOperationException("Currency conversion failed: API returned an error.");
            }

            return conversionData.ConversionResult;
        }
        catch (HttpRequestException ex)
        {
            throw new Exception("Failed to connect to the currency API.", ex);
        }
        catch (Exception ex)
        {
            throw new Exception("Error processing currency conversion.", ex);
        }
    }
}

Step 3: Usage example

// Convert 1 USD to INR
var converter = new CurrencyConverter();
try
{
    decimal result = await converter.ConvertAsync(1, "USD", "INR");
    Console.WriteLine($"1 USD = {result:N2} INR");
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}

Key Tips

  • Pick a reliable API: Look for services with free tiers, clear documentation, and stable uptime. Many require a free API key (just sign up to get one).
  • Reuse HttpClient: Creating a new HttpClient instance for every request can cause socket exhaustion—reuse a single instance instead.
  • Handle errors: Always add exception handling for network issues, invalid API responses, or authorization errors to make your code robust.

内容的提问来源于stack exchange,提问作者Dileep Prajapat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:32:47