In ASP.NET Core, caching is done using the IMemoryCache
interface. Unlike classic ASP.NET, it doesn’t have a built-in way to enumerate or remove all entries. But you can still manage to Purge ASP.NET Cache by:
Step 1: Use a Cache Wrapper with Keys Tracking
You must track all cache keys manually to remove them later.
public interface ICustomCache { void Set(string key, object value, TimeSpan duration); object Get(string key); void Remove(string key); void ClearAll(); } public class CustomMemoryCache : ICustomCache { private readonly IMemoryCache _cache; private readonly HashSet _cacheKeys = new(); public CustomMemoryCache(IMemoryCache cache) { _cache = cache; } public void Set(string key, object value, TimeSpan duration) { _cache.Set(key, value, duration); _cacheKeys.Add(key); } public object Get(string key) { return _cache.TryGetValue(key, out var value) ? value : null; } public void Remove(string key) { _cache.Remove(key); _cacheKeys.Remove(key); } public void ClearAll() { foreach (var key in _cacheKeys.ToList()) { _cache.Remove(key); _cacheKeys.Remove(key); } } }
Step 2: Register in Startup.cs (or Program.cs for .NET 6+)
builder.Services.AddMemoryCache(); builder.Services.AddSingleton<ICustomCache, CustomMemoryCache>();
Step 3: Use the Custom Cache Anywhere
public class AdminController : Controller { private readonly ICustomCache _cache; public AdminController(ICustomCache cache) { _cache = cache; } [HttpPost] [Authorize(Roles = "Admin")] public IActionResult ClearCache() { _cache.ClearAll(); return Ok("Cache cleared successfully."); } }
Security Best Practices
- Wrap cache-clearing behind authentication.
- Use role-based access for admins.
- Don’t expose this functionality in a public-facing UI.
(Visited 588 times, 1 visits today)