To send an SMS from an ASP.NET Core minimal API, register a typed client with AddHttpClient<T>, put the API key in its default headers, add a Polly-based retry through the resilience handler, and pass one Idempotency-Key per message so a retry can't send twice. The endpoint then calls the typed client and nothing else.

We make Ready, so the example uses the Ready REST API and only the request shape we document. If you're after plain C# without dependency injection, see our C# and .NET SMS guide. This post is about the minimal API wiring.

Register the typed client

HttpClientFactory manages handler lifetimes and avoids the socket exhaustion that comes from creating new HttpClient() per request. A typed client gives your endpoints one small class to depend on.

using System.Net;
using Microsoft.Extensions.Http.Resilience;
using Polly;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    .AddHttpClient<ReadySmsClient>(client =>
    {
        client.BaseAddress = new Uri("https://api.tryready.com");
        client.DefaultRequestHeaders.Add(
            "X-API-Key",
            builder.Configuration["READY_API_KEY"]
                ?? throw new InvalidOperationException("READY_API_KEY is not set"));
    })
    .AddResilienceHandler("ready-sms", pipeline =>
    {
        pipeline.AddRetry(new HttpRetryStrategyOptions
        {
            MaxRetryAttempts = 4,
            Delay = TimeSpan.FromMilliseconds(500),
            BackoffType = DelayBackoffType.Exponential,
            UseJitter = true,
            ShouldHandle = args => ValueTask.FromResult(args.Outcome switch
            {
                { Exception: HttpRequestException } => true,
                { Result.StatusCode: HttpStatusCode.TooManyRequests } => true,
                { Result.StatusCode: var s } => (int)s is 500 or 502 or 504,
                _ => false
            })
        });
        pipeline.AddTimeout(TimeSpan.FromSeconds(10));
    });

var app = builder.Build();

builder.Configuration["READY_API_KEY"] reads the environment variable of the same name, so the key never sits in source control. Throwing at startup beats discovering an empty key on the first customer text.

The Microsoft.Extensions.Http.Resilience package builds on Polly v8. The retry strategy re-sends a snapshot of the original request, so the Idempotency-Key header goes out unchanged on every attempt. That's what makes retrying a POST safe.

Notice what the predicate leaves out. A 503 from the API means the message was not sent, so retrying with the same key isn't the right move: resend with a new key instead. A 409 and the rest of the 4xx range aren't transient either, so the retry strategy ignores them and your code decides.

The typed client

using System.Net;
using System.Net.Http.Json;

public enum SmsOutcome { Sent, TimeRule, Rejected, NotSent }

public sealed class ReadySmsClient(HttpClient http)
{
    public async Task<SmsOutcome> SendAsync(
        string to, string body, string idempotencyKey, CancellationToken ct)
    {
        using var req = new HttpRequestMessage(HttpMethod.Post, "/v1/messages")
        {
            Content = JsonContent.Create(new
            {
                to,
                body,
                consent_attested = true
            })
        };
        req.Headers.Add("Idempotency-Key", idempotencyKey);

        using var res = await http.SendAsync(req, ct);
        if (res.IsSuccessStatusCode) return SmsOutcome.Sent;

        var text = await res.Content.ReadAsStringAsync(ct);
        if (res.StatusCode == HttpStatusCode.Conflict && text.Contains("QUIET_HOURS_BLOCK"))
            return SmsOutcome.TimeRule;
        if (res.StatusCode == HttpStatusCode.ServiceUnavailable)
            return SmsOutcome.NotSent;
        return SmsOutcome.Rejected;
    }
}

Set consent_attested to true only when the recipient agreed to texts, and take the value from your own consent data. to is E.164, and a 10-digit US number is treated as +1.

The client returns an outcome instead of throwing, because most of those results are normal business answers. A bad number or an opted-out contact isn't an exception, it's a result your endpoint should record.

The endpoint

app.MapPost("/orders/{id}/shipped", async (
    string id,
    ReadySmsClient sms,
    [FromHeader(Name = "Idempotency-Key")] string? callerKey,
    CancellationToken ct) =>
{
    var key = callerKey ?? Guid.NewGuid().ToString();
    var outcome = await sms.SendAsync(
        "+12125550199", $"Your order #{id} has shipped.", key, ct);

    return outcome switch
    {
        SmsOutcome.Sent => Results.Accepted(),
        SmsOutcome.TimeRule => Results.Problem("Resend once the recipient's window opens.", statusCode: 409),
        SmsOutcome.NotSent => Results.Problem("Not sent. Retry with a new key.", statusCode: 503),
        _ => Results.Problem("The number was rejected.", statusCode: 422)
    };
});

app.Run();

(Add using Microsoft.AspNetCore.Mvc; for FromHeader.) The endpoint accepts a caller-supplied Idempotency-Key and forwards it. If your own caller retries your endpoint, the same key reaches the API and the text isn't sent again. When the caller supplies none, we generate one, which only protects the retries inside this request.

Where each piece lives

ConcernHomeWhy
Base address and API keyAddHttpClient optionsOne place, read from configuration
Retry and timeoutAddResilienceHandlerPolicy stays out of business code
Request shape and status mappingReadySmsClientEasy to fake in tests
Key for a messageThe caller or the endpointDecided once, before attempt one

A 409 QUIET_HOURS_BLOCK is a time rule, not a failure. An API text is held only if the window opens within a few hours, so otherwise you resend it once the window opens. Our retries guide has the whole status table.

Long work belongs in a queue

A retry loop inside a web request is fine for a one-off the user is waiting on. If the text must arrive and the request can't wait, register the typed client in a BackgroundService that reads from a Channel<T> or your queue of choice, and keep the key on the queued item. The queue design guide covers the trade-offs.

FAQ

Do I need Polly directly?

No. Microsoft.Extensions.Http.Resilience brings it in. Call AddResilienceHandler and you're using Polly's strategies without referencing the types otherwise.

Can I use AddStandardResilienceHandler instead?

You can, and it's a good default for GET calls. For this POST we prefer the explicit retry, because the standard predicate would also retry a 503, which the API documents as not sent.

How do I test the endpoint?

Replace the typed client's primary handler with a fake HttpMessageHandler in WebApplicationFactory, return a 500 then a 200, and assert the same Idempotency-Key on both. Our mocking guide shows the pattern.

The short version

One typed client, one retry policy, one key per message. The messages API docs list every field, and you can create an account to get a key.