Build an ASP.NET Core app
In five minutes you'll build a small API that stores a user, publishes updates, and reads two values in one round trip. You need the .NET 11 SDK and a Redis-compatible server. Docker is enough.
The quick start is a two-minute console app.
1. Create the app
dotnet new web -n RespireQuickstart -f net11.0
cd RespireQuickstart
dotnet add package Respire.DependencyInjection
Respire.DependencyInjection brings in the core Respire package, so nothing else is needed. See choose packages for optional add-ons, and versioning for release candidates.
If you do not already have a local server, start one:
docker run --name respire-quickstart-redis --rm -d -p 127.0.0.1:6379:6379 redis:7-alpine
2. Replace Program.cs
Copy this entire file. AddRespire gives every endpoint the same client and disposes it at shutdown. It connects on the first command.
using System.Text.Json.Serialization;
using Respire;
using Respire.DependencyInjection;
using Respire.Serialization;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRespire(_ => new RespireOptions
{
Endpoints = { new RespireEndpoint("localhost") },
Serializer = RespireSystemTextJsonSerializer.FromContext(AppJsonContext.Default),
});
builder.Services.ConfigureHttpJsonOptions(options =>
options.SerializerOptions.TypeInfoResolverChain.Insert(0, AppJsonContext.Default));
await using var app = builder.Build();
app.MapPost("/users/{id}", async (string id, User user, IRespireClient redis, CancellationToken ct) =>
{
await redis.SetAsync($"quickstart:user:{id}", user,
expiry: TimeSpan.FromMinutes(30), cancellationToken: ct);
await redis.PublishAsync("quickstart:updates", $"Saved user {id}", ct);
return Results.NoContent();
});
app.MapGet("/users/{id}", async (string id, IRespireClient redis, CancellationToken ct) =>
{
User? user = await redis.GetAsync<User>($"quickstart:user:{id}", ct);
return user is null ? Results.NotFound() : Results.Ok(user);
});
app.MapGet("/stats", async (IRespireClient redis, CancellationToken ct) =>
{
using var batch = redis.CreateBatch();
var user = batch.Get<User>("quickstart:user:ada");
var visits = batch.Increment("quickstart:visits");
await batch.ExecuteAsync(ct);
return Results.Ok(new Stats(user.Result, visits.Result));
});
// Subscribe before accepting requests, so the first POST can be observed.
var client = app.Services.GetRequiredService<IRespireClient>();
await using var subscription = await client.SubscribeAsync("quickstart:updates");
var listener = LogUpdatesAsync(subscription, app.Lifetime.ApplicationStopping);
try
{
await app.RunAsync();
}
finally
{
await subscription.DisposeAsync();
await listener;
}
static async Task LogUpdatesAsync(RespireSubscription subscription, CancellationToken ct)
{
try
{
await foreach (var message in subscription.WithCancellation(ct))
{
if (message.Kind == RespireMessageKind.Message)
Console.WriteLine(message.Text);
else
Console.WriteLine("Updates were missed; read the current user from Redis.");
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { }
}
public sealed record User(string Name, int LoginCount);
public sealed record Stats(User? User, long Visits);
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(User))]
[JsonSerializable(typeof(Stats))]
internal partial class AppJsonContext : JsonSerializerContext;
The JSON context generates metadata for your POCOs. RespireSystemTextJsonSerializer.FromContext makes Respire's serializer safe for trimming and NativeAOT; the HTTP endpoints use the same metadata. Publishing this whole app as NativeAOT has additional serialization and analyzer requirements.
The subscriber prints notifications to the app's terminal. Pub/sub is live delivery, so missed messages are not replayed; pub/sub explains reconnects and delivery gaps. The batch queues both commands before ExecuteAsync; read .Result only after execution finishes. A batch is not an atomic transaction.
3. Run it
dotnet run --urls http://localhost:5050
In another terminal, create user.json containing:
{"name":"Ada","loginCount":7}
Then run these commands from that file's directory (in Windows PowerShell, use curl.exe):
curl -i -X POST http://localhost:5050/users/ada -H "Content-Type: application/json" --data-binary "@user.json"
curl http://localhost:5050/users/ada
curl http://localhost:5050/stats
The POST returns 204 No Content, and the app prints Saved user ada. The GET returns {"name":"Ada","loginCount":7}. With a fresh Redis server, on the first /stats request, the response is {"user":{"name":"Ada","loginCount":7},"visits":1}; subsequent calls increase visits.
Stop the app with Ctrl+C. If you started the walkthrough's Docker container, stop it too:
docker stop respire-quickstart-redis
Start from a template
Prefer a working project to copy from? Respire.Templates includes three starters.
Cache-aside API
Install the templates with the .NET 11 SDK. Replace <exact-version> with the version
from the latest GitHub release:
dotnet new install Respire.Templates@<exact-version>
dotnet new respire-api -n MyCacheApi
cd MyCacheApi
docker compose up -d --wait
dotnet run
Open http://localhost:5080/health/ready, then request
http://localhost:5080/values/hello twice. The API caches a generated value for five
minutes. Replace its factory with your database or service lookup. The starter
includes a shared DI client, Redis readiness checks, and OpenTelemetry traces and
metrics. Set OTEL_EXPORTER_OTLP_ENDPOINT to enable export to your collector.
The container requires Docker Compose and uses Redis 8. Set
ConnectionStrings__Redis to use an existing Redis 7+ server instead.
Stop the app with Ctrl+C and run docker compose down to remove the local container.
The generated README covers configuration and custom HTTP ports.
Aspire starter
After installing the same template package, use respire-aspire for an AppHost
and minimal API with an Aspire-managed Redis container. The generated solution
restores its Respire packages from NuGet at the installed template version.
dotnet new respire-aspire -n MyRedisApp
cd MyRedisApp
dotnet build MyRedisApp.slnx
cd MyRedisApp.AppHost
aspire start --non-interactive
aspire wait api --non-interactive --timeout 120
aspire describe --non-interactive
You need .NET SDK 11.0.100 or later, Aspire CLI
17.0 or later, a running Docker-compatible runtime, and a trusted development
certificate (dotnet dev-certs https --trust). The starter uses Aspire 17.0.0
hosting packages and Redis 8.10. Add --isolated to aspire start when running
multiple copies.
Use the API HTTP URL shown by describe or the dashboard; ports are dynamic.
WithReference supplies Redis credentials and WaitFor gates API startup on
Redis readiness. The API establishes its client connection before serving
/health/ready; /health/live checks only the running API. Send a JSON string to
PUT /values/hello, then call GET /values/hello to read it back. Values expire
after five minutes; a missing value returns HTTP 404.
Respire.Aspire registers the client, Redis health check, and Respire traces and
metrics. Logs and telemetry export to the Aspire dashboard through its injected
OTLP configuration. See the generated README for runnable requests and
Aspire integration for configuration options.
Run aspire stop --non-interactive from the AppHost directory to stop its API,
dashboard and Redis container. This starter uses no persistent volume, so Redis
data is discarded. For a larger example including Valkey and HTTP caching, see
the Aspire sample.
Templates are shipped with Respire releases. Generated Respire package references
use that same version. To remove the templates, run
dotnet new uninstall Respire.Templates.
Job worker and dashboard
The same package includes respire-worker, a standalone .NET 11 app with a typed
job queue, sample handler, enqueue API and operator dashboard:
dotnet new respire-worker -n MyWorker
cd MyWorker
docker compose up -d --wait
export Dashboard__Password='replace-with-your-own-password'
dotnet run
In PowerShell, set $env:Dashboard__Password = 'replace-with-your-own-password'
instead of export. Open http://localhost:5080/workers/ and sign in as operator
with that password. No default password is shipped. The sample uses HTTP Basic
authentication with the QueueOperators authorization policy; plain HTTP credentials
are accepted only on loopback in Development. Before deployment, configure HTTPS
and replace the sample authentication handler with your identity provider.
From another terminal, enqueue a job and read its result (curl prompts for your password):
curl -u operator -H 'Content-Type: application/json' -d '{"message":"hello worker"}' http://localhost:5080/jobs/welcome-1
curl -u operator http://localhost:5080/jobs/welcome-1
Use curl.exe in Windows shells that alias curl. The handler stores HELLO WORKER
in Redis for one hour and acknowledges the job. GET returns 404 until the result
exists or after it expires. Reusing the same job ID within one day deduplicates
enqueue; handlers must still tolerate redelivery. The dashboard retains its
authorization and antiforgery checks for operator actions.
Set ConnectionStrings__Redis for an existing Redis server, or use the generated
Compose file. /health/ready checks Redis connectivity. Set
OTEL_EXPORTER_OTLP_ENDPOINT to export client and worker traces and metrics.
The generated README explains handler customization, queue retention, ports and
authentication. Stop the app with Ctrl+C, then run docker compose down; removing
the local Redis container discards queued jobs and results.
Keep going
- Dependency injection: configuration and named clients.
- Connections: connection strings, credentials, TLS, and timeouts.
- Values and serialization: typed values and NativeAOT.
- Pub/sub: channels, cancellation, and delivery gaps.
- Batches and transactions: queued results and atomic operations.
- Strings and keys: explore more commands when you need them.