Tutorial/C# i .NET

Kursy walut w C# i .NET

Zbuduj typowanego klienta .NET z IHttpClientFactory, decimal, anulowaniem i ograniczonym timeoutem.

MMexchangerate.dev·Jul 17, 2026·6 min czytania

Zarejestruj typowany HttpClient, wstrzyknij klucz z konfiguracji i deserializuj kursy do decimal. Przekazuj anulowanie w całym wywołaniu.

Key points
Użyj IHttpClientFactory.
Deserializuj kursy do decimal.
Przekazuj CancellationToken i ustaw timeout.
Wywołaj EnsureSuccessStatusCode() przed dekodowaniem.

Zarejestruj typowanego HttpClient

Rejestracja ustala URL, bearer token i timeout. Klient zachowuje kontrakt odpowiedzi i przekazuje anulowanie.

csharp · Program.cs and FxClient.cscopy
// Program.cs
using System.Net.Http.Headers;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpClient<FxClient>(client =>
{
    var key = builder.Configuration["EXCHANGERATE_API_KEY"]
        ?? throw new InvalidOperationException("EXCHANGERATE_API_KEY is missing");

    client.BaseAddress = new Uri("https://api.exchangerate.dev/v1/");
    client.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", key);
    client.Timeout = TimeSpan.FromSeconds(5);
});

// FxClient.cs
using System.Net.Http.Json;
using System.Text.Json.Serialization;

public sealed record LatestRates(
    string Base,
    string Source,
    [property: JsonPropertyName("market_session")] string MarketSession,
    [property: JsonPropertyName("data_updated_at")] DateTimeOffset DataUpdatedAt,
    Dictionary<string, decimal> Rates
);

public sealed class FxClient(HttpClient http)
{
    public async Task<LatestRates> GetLatestAsync(
        string baseCurrency,
        CancellationToken cancellationToken)
    {
        using var response = await http.GetAsync(
            $"latest/{baseCurrency}?symbols=EUR,GBP",
            cancellationToken);

        response.EnsureSuccessStatusCode();

        return await response.Content.ReadFromJsonAsync<LatestRates>(
            cancellationToken: cancellationToken)
            ?? throw new InvalidOperationException("Empty FX response");
    }
}

Przekaż anulowanie z żądania

csharp · endpoint usagecopy
var app = builder.Build();

app.MapGet("/fx", async (
    FxClient fx,
    CancellationToken cancellationToken) =>
{
    var rates = await fx.GetLatestAsync("USD", cancellationToken);

    return Results.Ok(new {
        eur = rates.Rates["EUR"],
        rates.Source,
        rates.MarketSession,
        rates.DataUpdatedAt,
    });
});

app.Run();

Buforuj tylko poprawne obserwacje

Buforuj pełną obserwację, nie tylko Rates["EUR"]. Zachowaj Source, MarketSession i DataUpdatedAt.

Zawęź politykę ponowień
Ponawiaj krótkie błędy sieci i wybrane 5xx. Nie traktuj 401 jako przejściowego i nie twórz lawiny po 429.
  • Utrzymuj jedną rejestrację klienta.
  • Używaj decimal.
  • Przekazuj anulowanie.
  • Odrzucaj błędy przed deserializacją.
MM
exchangerate.dev
Przewodniki integracyjne dla programistów pracujących z danymi FX.

Keep reading

GuideHistoryczne szeregi FX w jednym wywołaniuRead ReferenceJak czytać source i market_sessionRead GuideKurs orientacyjny a wykonywalnyRead