Tutorial/C# และ .NET

อัตราแลกเปลี่ยนใน C# และ .NET

สร้าง client .NET ด้วย IHttpClientFactory, decimal, cancellation และ timeout

ERexchangerate.dev·Jul 17, 2026·อ่าน 6 นาที

ลงทะเบียน HttpClient แบบ typed อ่าน key จาก config และแปลงอัตราเป็น decimal พร้อมส่ง cancellation ต่อไป เพื่อไม่ให้คำขอที่ช้าค้างการเชื่อมต่อไว้ไม่จำกัดเวลา

Key points
ใช้ IHttpClientFactory
ใช้อัตราแบบ decimal
ส่ง CancellationToken และตั้ง timeout
เรียก EnsureSuccessStatusCode() ก่อนอ่าน JSON

ลงทะเบียน HttpClient แบบ typed

การลงทะเบียนกำหนด URL, bearer token และ timeout ส่วน client รักษาสัญญา response และ cancellation

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");
    }
}

ส่ง cancellation จากคำขอ

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();

แคชเฉพาะข้อมูลที่สำเร็จ

แคชข้อมูลครบพร้อม Source, MarketSession และ DataUpdatedAt ไม่ใช่แค่ Rates["EUR"]

จำกัดนโยบาย retry
retry เฉพาะ network error สั้นๆ และ 5xx บางรายการ ไม่ retry 401 หรือสร้างคำขอถี่หลัง 429
  • ใช้ client registration เดียว
  • ใช้ decimal
  • ส่ง cancellation
  • ปฏิเสธ error ก่อน deserialize
ER
exchangerate.dev
คู่มือเชื่อมต่อสำหรับนักพัฒนาที่ใช้ข้อมูล FX

อ่านต่อ

Guideข้อมูล FX ย้อนหลังในคำขอเดียวอ่าน Referenceอ่าน source และ market_sessionอ่าน Guideอัตราเพื่ออ้างอิงและอัตราที่ซื้อขายได้อ่าน
เปรียบเทียบเพิ่มเติมFixer vs exchangerate.devOpen Exchange Rates vs exchangerate.devCurrencylayer vs exchangerate.dev
เรียนรู้Reading source and market_session in your pipelineIndicative vs executable FX rates: what a rates API actually gives youECB reference rates, explained
อัตราสดEUR/USDGBP/USDUSD/JPY