6

I'm storing some key generated by users in a IDistributedCache set up.

The key are long lived and they can be manually revoked by an user, if the user knows each one of them:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDistributedMemoryCache();
    //...
}

//ControllerBase:

//Adding the key:
await _cache.SetAsync(userKey, userId, new DistributedCacheEntryOptions 
{ 
    AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(10)
});

//Removing the key:
await _cache.RemoveAsync(key);

Now, what I want to do is to be able to list all keys still present in the cache that were created by one of the users. Also, I want to be able to bulk delete them.

Is there such a functionality available right now? Maybe with cancelation tokens? How can I do that?

Nicke Manarin
  • 3,026
  • 4
  • 37
  • 79

2 Answers2

8

No, you can only work with one key at a time with IDistributedCache. Mass key eviction and similar scenarios are beyond the scope of this facade. If you need to handle more advanced scenarios, then you should connect to your cache directly, using the appropriate client. For example, for a Redis backing, you can use the StackExchange.Redis package, and issue whatever commands you like via that.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
1

You can flush the store using FLUSHALL method(IServer.FlushAllDatabasesAsync() - please note that AllowAdmin flag must be true in the config). The method exist in IServer interface which can be retrieved from IConnectionMultiplexer. If you're using StackExchange.Redis DI, IDistributedCache doesn't have the ability to do so as of now. You can use System.Reflection to get IConnectionMultiplexer from (RedisCache)IDistributedCache.