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.
builder.Services.AddSwrForAspNetCore();Optionally configure global defaults:
builder.Services.AddSwrForAspNetCore(options =>{ options.StaleTime = TimeSpan.FromSeconds(30); options.CacheTime = TimeSpan.FromMinutes(5);});Using ISwr in Controllers
Section titled “Using ISwr in Controllers”Inject ISwr via primary constructor (C# 12+):
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.Completedwaits until data arrives - On cache hit (within
StaleTime): the response is instant — no fetcher call - On stale hit (past
StaleTime, withinCacheTime): stale data is returned immediately while a background revalidation runs - Always check
result.Errorbefore accessingresult.Data— a failed fetch setsErrorwithout throwing
Using ISwr in Minimal APIs
Section titled “Using ISwr in Minimal APIs”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);});Cache Sharing
Section titled “Cache Sharing”Because ISwr is a Singleton, the cache is shared across all requests:
- Request A fetches
/api/external/products→ cache miss → fetcher called → result cached - Request B (within
StaleTime) fetches the same key → cache hit → instant response, no fetcher call - Request C (past
StaleTime, withinCacheTime) → stale data returned immediately → background revalidation starts - Request D (past
CacheTime) → cache miss → full fetch via fetcher
Mutations and Cache Invalidation
Section titled “Mutations and Cache Invalidation”MutateAsync
Section titled “MutateAsync”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");Manual Invalidation
Section titled “Manual Invalidation”Force a cache refresh without executing a mutation:
swr.Invalidate("/api/external/products"); // Remove one exact keyswr.InvalidateByPrefix("/api/external/products"); // Remove all keys with this prefixswr.InvalidateAll(); // Clear the entire cacheDisposal
Section titled “Disposal”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.
Next Steps
Section titled “Next Steps”- Getting Started — Installation and first example
- Blazor Integration — Scoped cache, revalidation callbacks, mutations
- API Reference — Complete documentation for all public types