A .NET 8 Razor Pages / MVC hybrid sample demonstrating a lightweight URL redirection system backed by an in-memory cache and a pluggable redirect source. It shows how to centralize legacy URL handling without scattering rewrite logic across the app.
- Central RedirectUrlService for resolving old -> new URLs.
- Pluggable IRedirectUrlProvider so redirects can come from config, database, JSON, etc.
- In-memory caching via IMemoryCache with configurable refresh + expiration.
- Periodic background refresh using System.Threading.Timer.
- Supports absolute or relative target URLs (URLTypeEnum).
- Clean separation in MiddlewareLibrary for reuse across applications.
- A request arrives.
- Your middleware or controller (you add this) calls IRedirectUrlService.GetRedirect(path).
- If a match exists, you issue a 301/302 to Redirect.NewUrl.
- The service maintains a cached list of Redirect entries, auto-refreshed on an interval.
- Refresh interval: RedirectCacheRefreshMinutes (background timer repopulates cache).
- Expiration: RedirectCacheExpireMinutes (absolute expiration for the cache entry).
- If the cache is empty on first use, it is populated synchronously.
Configure both to balance memory freshness vs. performance.
In appsettings.json (example):
Provide your source of truth by implementing IRedirectUrlProvider:
public class RedirectMiddleware
{
private readonly RequestDelegate _next;
private readonly IRedirectUrlService _redirectUrlService;
public RedirectMiddleware(RequestDelegate next, IRedirectUrlService redirectUrlService)
{
_next = next;
_redirectUrlService = redirectUrlService;
}
public async Task InvokeAsync(HttpContext context)
{
var path = context.Request.Path.Value;
var redirect = _redirectUrlService.GetRedirect(path);
if (redirect != null)
{
context.Response.Redirect(redirect.NewUrl, redirect.Permanently);
return;
}
await _next(context);
}
}
Navigate to: https://localhost:5001 (or shown port).
RedirectUrlService logs:
- Cache refresh operations.
- Cache hits.
- Failed provider calls (if exceptions logged externally).
Bootstrap, jQuery, and validation scripts are included under their respective MIT licenses (see /wwwroot/lib/*/LICENSE).
This sample code is MIT licensed (adjust if you add a license file). Third-party libraries retain their original licenses.
- Add real redirect provider.
- Add unit tests around RedirectUrlService.
- Add admin UI for managing redirects (optional).
Happy building!