# C# client for .NET 10: HttpClient, await using, no packages

> A single class on top of HttpClient. Orders come back as an IAsyncDisposable, so await using finishes or cancels the order on every exit path. Money is decimal and parsed with the invariant culture, which matters more than it sounds on a German or Russian build agent.

Source: https://otpwatch.com/csharp
Updated: 2026-11-24
API key: https://otpwatch.com/agent/key

## The client

```csharp title="SmsClient.cs"
// handler_api reference: https://otpwatch.com/csharp
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
using System.Globalization;

namespace Otp;

public sealed class SmsApiException(string reply) : Exception(reply)
{
    public string Reply { get; } = reply;
    public string Code { get; } = reply.Split(':', 2)[0];
}

public sealed class SmsClient(HttpClient http, string apiKey)
{
    public const string DefaultBaseUrl = "https://sim-aggregator.org/stubs/handler_api.php";

    public async Task<string> CallAsync(string action, IDictionary<string, string?>? args = null, CancellationToken ct = default)
    {
        var query = $"?action={action}&api_key={Uri.EscapeDataString(apiKey)}";
        foreach (var (k, v) in args ?? new Dictionary<string, string?>())
            if (v is not null) query += $"&{k}={Uri.EscapeDataString(v)}";

        for (var attempt = 0; attempt < 6; attempt++)
        {
            using var res = await http.GetAsync(query, ct);
            res.EnsureSuccessStatusCode();
            var text = (await res.Content.ReadAsStringAsync(ct)).Trim();
            if (text != "REQUEST_LIMIT") return text;
            var backoff = TimeSpan.FromSeconds(Math.Min(Math.Pow(2, attempt), 30)) + TimeSpan.FromMilliseconds(Random.Shared.Next(500));
            await Task.Delay(backoff, ct);
        }
        throw new SmsApiException("REQUEST_LIMIT");
    }

    public async Task<decimal> GetBalanceAsync(CancellationToken ct = default)
    {
        var reply = await CallAsync("getBalance", ct: ct);
        if (!reply.StartsWith("ACCESS_BALANCE:")) throw new SmsApiException(reply);
        return decimal.Parse(reply["ACCESS_BALANCE:".Length..], CultureInfo.InvariantCulture);
    }

    public async Task<Activation> OrderAsync(string service, int country, decimal? maxPrice = null,
        string? duration = null, CancellationToken ct = default)
    {
        var reply = await CallAsync("getNumber", new Dictionary<string, string?>
        {
            ["service"] = service,
            ["country"] = country.ToString(CultureInfo.InvariantCulture),
            ["maxPrice"] = maxPrice?.ToString(CultureInfo.InvariantCulture),
            ["duration"] = duration,
        }, ct);
        if (!reply.StartsWith("ACCESS_NUMBER:")) throw new SmsApiException(reply);
        var parts = reply.Split(':', 3);
        return new Activation(this, parts[1], parts[2]);
    }

    internal Task<string> SetStatusAsync(string id, int status, CancellationToken ct = default) =>
        CallAsync("setStatus", new Dictionary<string, string?> { ["id"] = id, ["status"] = status.ToString() }, ct);

    internal Task<string> GetStatusAsync(string id, CancellationToken ct) =>
        CallAsync("getStatus", new Dictionary<string, string?> { ["id"] = id }, ct);
}

public sealed class Activation(SmsClient client, string id, string phone) : IAsyncDisposable
{
    public string Id { get; } = id;
    public string Phone { get; } = phone;           // without '+'
    public string E164 => "+" + Phone;
    public string? Code { get; private set; }

    public async Task<string> WaitCodeAsync(TimeSpan timeout, TimeSpan? interval = null, CancellationToken ct = default)
    {
        using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
        cts.CancelAfter(timeout);
        try
        {
            while (true)
            {
                var reply = await client.GetStatusAsync(Id, cts.Token);
                if (reply.StartsWith("STATUS_OK:")) return Code = reply["STATUS_OK:".Length..];
                if (!reply.StartsWith("STATUS_WAIT")) throw new SmsApiException(reply);
                await Task.Delay(interval ?? TimeSpan.FromSeconds(3), cts.Token);
            }
        }
        catch (OperationCanceledException) when (!ct.IsCancellationRequested)
        {
            throw new TimeoutException($"No SMS for activation {Id} within {timeout}.");
        }
    }

    public async Task RequestAnotherCodeAsync(CancellationToken ct = default)
    {
        await client.SetStatusAsync(Id, 3, ct);
        Code = null;
    }

    // Our choice, not an API rule: the docs only say "too early to cancel, repeat the request later".
    private const int CancelTries = 9;
    private static readonly TimeSpan CancelPause = TimeSpan.FromSeconds(10);

    public async ValueTask DisposeAsync()
    {
        if (Code is not null) { await client.SetStatusAsync(Id, 6); return; }
        for (var i = 0; i < CancelTries; i++)
        {
            if (await client.SetStatusAsync(Id, 8) != "EARLY_CANCEL_DENIED") return;
            if (i < CancelTries - 1) await Task.Delay(CancelPause);   // too early to cancel: repeat later
        }
        throw new InvalidOperationException(
            $"Activation {Id}: cancel still EARLY_CANCEL_DENIED after {CancelTries} tries; cancel it later.");
    }
}
```

## Use it

```env title=".env.example"
# handler_api reference: https://otpwatch.com/csharp
# Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
SMS_API_BASE_URL=https://sim-aggregator.org/stubs/handler_api.php
# Key from the SimAggregator dashboard: https://otpwatch.com/agent/key
SMS_API_KEY=
```

```csharp title="Program.cs"
// handler_api reference: https://otpwatch.com/csharp
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
using Otp;

var baseUrl = Environment.GetEnvironmentVariable("SMS_API_BASE_URL") ?? SmsClient.DefaultBaseUrl;
using var http = new HttpClient { BaseAddress = new Uri(baseUrl), Timeout = TimeSpan.FromSeconds(30) };
var sms = new SmsClient(http, Environment.GetEnvironmentVariable("SMS_API_KEY") ?? throw new InvalidOperationException("SMS_API_KEY is not set"));

Console.WriteLine($"balance: {await sms.GetBalanceAsync()}");
try
{
    await using var act = await sms.OrderAsync("tg", 16, maxPrice: 2.00m);   // Telegram, United Kingdom
    Console.WriteLine($"number: {act.E164}");
    // ... make the app under test send the SMS to act.E164 ...
    Console.WriteLine($"code: {await act.WaitCodeAsync(TimeSpan.FromMinutes(5))}");
}
catch (SmsApiException e) when (e.Code is "NO_NUMBERS" or "WRONG_MAX_PRICE" or "NO_BALANCE")
{
    Console.WriteLine($"not ordered: {e.Reply}");
}
```

`await using` runs `DisposeAsync` when the block exits: `setStatus` 6 if a code was read, otherwise a cancel that is repeated every 10 seconds while the API answers `EARLY_CANCEL_DENIED` and throws after nine tries (the docs give no wait, so both numbers are yours to change). Note that a relative query (`"?action=..."`) resolves against `BaseAddress`, so the base URL must be the full `handler_api.php` path.

## Registering it in ASP.NET Core

```csharp title="Program.cs (web)"
// handler_api reference: https://otpwatch.com/csharp
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
builder.Services.AddHttpClient("sms", c =>
{
    c.BaseAddress = new Uri(builder.Configuration["SMS_API_BASE_URL"] ?? SmsClient.DefaultBaseUrl);
    c.Timeout = TimeSpan.FromSeconds(30);
});
builder.Services.AddSingleton(sp => new SmsClient(
    sp.GetRequiredService<IHttpClientFactory>().CreateClient("sms"),
    builder.Configuration["SMS_API_KEY"] ?? throw new InvalidOperationException("SMS_API_KEY missing")));
```

Locally, `dotnet user-secrets set "SMS_API_KEY" "..."` keeps the key out of appsettings.json. In production set the `SMS_API_KEY` environment variable or read it from your vault; the default configuration reads environment variables under the same name. Do not poll from inside a request handler: queue the activation id and let a `BackgroundService` wait for the code.

## Tests with a stub handler

```csharp title="SmsClientTests.cs"
// handler_api reference: https://otpwatch.com/csharp
// Building a bot that resells numbers to other people? Software program: https://otpwatch.com/agent/partner
using System.Net;
using Otp;
using Xunit;

sealed class ScriptedHandler(params string[] replies) : HttpMessageHandler
{
    private readonly Queue<string> _replies = new(replies);
    public List<string> Queries { get; } = [];

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
    {
        Queries.Add(request.RequestUri!.Query);
        return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(_replies.Dequeue()) });
    }
}

public class SmsClientTests
{
    private static (SmsClient, ScriptedHandler) Make(params string[] replies)
    {
        var h = new ScriptedHandler(replies);
        return (new SmsClient(new HttpClient(h) { BaseAddress = new Uri(SmsClient.DefaultBaseUrl) }, "k"), h);
    }

    [Fact]
    public async Task Keeps_leading_zeros_and_finishes()
    {
        var (sms, h) = Make("ACCESS_NUMBER:9:447700900123", "STATUS_WAIT_CODE", "STATUS_OK:004821", "ACCESS_ACTIVATION");
        await using (var act = await sms.OrderAsync("tg", 16))
            Assert.Equal("004821", await act.WaitCodeAsync(TimeSpan.FromSeconds(5), TimeSpan.Zero));
        Assert.Contains("status=6", h.Queries[^1]);
    }

    [Fact]
    public async Task Parses_balance_with_invariant_culture()
    {
        var (sms, _) = Make("ACCESS_BALANCE:12.50");
        Assert.Equal(12.50m, await sms.GetBalanceAsync());
    }
}
```

## Notes

- `decimal.Parse` with `CultureInfo.InvariantCulture` is not optional: on a machine with a comma decimal separator, `decimal.Parse("12.50")` reads 1250.
- `maxPrice` is formatted the same way, so `2.00m` goes out as `2.00`, never `2,00`.
- For Selenium in C#, wrap `OrderAsync` in your test fixture and dispose it in teardown; the [Selenium page](https://otpwatch.com/selenium-otp-testing.md) shows the pattern in Python.
- Rentals: pass `duration: "d1"`, `"d3"` or `"d7"`; see [renting a number](https://otpwatch.com/rent-number-api.md).
