Skip to content

ASP.NET Core Integration

Swr.Net works as a server-side caching layer in ASP.NET Core. AddSwrForAspNetCore() registers ISwr as a Singleton, so the cache is shared across all HTTP requests. Use it to cache upstream API calls, database queries, or any expensive data source — requests benefit from cached results without hitting the upstream on every call.

Program.cs
builder.Services.AddSwrForAspNetCore();

Optionally configure global defaults:

Program.cs
builder.Services.AddSwrForAspNetCore(options =>
{
options.StaleTime = TimeSpan.FromSeconds(30);
options.CacheTime = TimeSpan.FromMinutes(5);
});

Inject ISwr via primary constructor (C# 12+):

Controllers/ProductsController.cs
using System.Net.Http.Json;
using Swr.Net;
[ApiController]
[Route("api/[controller]")]
public class ProductsController(ISwr swr, IHttpClientFactory httpFactory) : ControllerBase
{
private readonly HttpClient _http = httpFactory.CreateClient("upstream");
[HttpGet]
public async Task<IActionResult> GetAll()
{
var result = swr.Use<List<Product>>("/api/external/products",
async key => await _http.GetFromJsonAsync<List<Product>>(key));
await result.Completed;
if (result.Error is not null)
return StatusCode(503, new { error = result.Error });
return Ok(result.Data);
}
[HttpGet("{id}")]
public async Task<IActionResult> GetById(int id)
{
var result = swr.Use<Product>($"/api/external/products/{id}",
async key => await _http.GetFromJsonAsync<Product>(key));
await result.Completed;
if (result.Error is not null)
return StatusCode(503, new { error = result.Error });
if (result.Data is null)
return NotFound();
return Ok(result.Data);
}
}

How it works:

  • On cache miss: Use<T> fires the fetcher in the background; await result.Completed waits until data arrives
  • On cache hit (within StaleTime): the response is instant — no fetcher call
  • On stale hit (past StaleTime, within CacheTime): stale data is returned immediately while a background revalidation runs
  • Always check result.Error before accessing result.Data — a failed fetch sets Error without throwing
Program.cs
builder.Services.AddSwrForAspNetCore(options =>
{
options.StaleTime = TimeSpan.FromSeconds(30);
options.CacheTime = TimeSpan.FromMinutes(5);
});
builder.Services.AddHttpClient("upstream", client =>
{
client.BaseAddress = new Uri("https://api.example.com");
});
var app = builder.Build();
app.MapGet("/api/products", async (ISwr swr, IHttpClientFactory httpFactory) =>
{
var http = httpFactory.CreateClient("upstream");
var result = swr.Use<List<Product>>("/api/external/products",
async key => await http.GetFromJsonAsync<List<Product>>(key));
await result.Completed;
return result.Error is not null
? Results.Problem(result.Error)
: Results.Ok(result.Data);
});

Because ISwr is a Singleton, the cache is shared across all requests:

  1. Request A fetches /api/external/products → cache miss → fetcher called → result cached
  2. Request B (within StaleTime) fetches the same key → cache hit → instant response, no fetcher call
  3. Request C (past StaleTime, within CacheTime) → stale data returned immediately → background revalidation starts
  4. Request D (past CacheTime) → cache miss → full fetch via fetcher

Use MutateAsync to execute a mutation and invalidate related cache entries:

await swr.MutateAsync(
async () => await http.PostAsJsonAsync("/api/external/products", newProduct),
"/api/external/products"
);

Force a cache refresh without executing a mutation:

swr.Invalidate("/api/external/products"); // Remove one exact key
swr.InvalidateByPrefix("/api/external/products"); // Remove all keys with this prefix
swr.InvalidateAll(); // Clear the entire cache

In ASP.NET Core with Singleton registration, ISwr lives for the lifetime of the application. You do not need to manually dispose it — the DI container handles disposal when the application shuts down. SwrResult<T> does not implement IDisposable, so per-request responses require no cleanup.