'Bust the [ResponseCache] attribute

Back in the ASP.NET MVC days (Not Core) - I used the [ResponseCache] attribute and I was able to BUST this cache when I wanted -

How do you guys bust [ResponseCache] in .NET Core?

This is how I've done it in MVC

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Caching;


namespace Whatever.Web.Util
{
public static class OutputCacheInvalidator
{
public static void Remove(string[] urls)
{
    foreach (var url in urls)
    {
        HttpResponse.RemoveOutputCacheItem(url);
    }
}

public static void SearchAndRemove(string[] keywords)
{
    var runtimeType = typeof(Cache);
    var internalCache = runtimeType.GetProperty(
        "InternalCache",
        BindingFlags.Instance | BindingFlags.NonPublic);

    if (internalCache == null || !(internalCache.GetValue(HttpRuntime.Cache) is CacheStoreProvider cache))
    {
        return;
    }

    var enumerator = cache.GetEnumerator();
    var keysToRemove = new List<string>();

    while (enumerator.MoveNext())
    {
        if (enumerator.Key == null)
        {
            continue;
        }

        var key = enumerator.Key.ToString();

        if (keywords.Any(keyword => key.IndexOf(keyword, StringComparison.OrdinalIgnoreCase) >= 0))
        {
            keysToRemove.Add(key);
        }
    }

    foreach (var key in keysToRemove)
    {
        cache.Remove(key);
    }
}

} }



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source