I'm building an ASP.NET Core 8 MVC site relying on OutputCache. The implementations is pretty standard and works just fine.
E.g.
[OutputCache(PolicyName = "MyCachePolicy")]
public ActionResult Index(SubPageType currentPage)
{
// ...
return View(currentPage);
}
It is all injected using an IServiceCollection
extension method:
options.AddPolicy(profile.Key, builder =>
{
builder.Tag(profile.Key);
builder.SetVaryByRouteValue(profile.Value?.VaryByRouteValueNames);
builder.SetVaryByQuery(profile.Value.VaryByQueryKeys);
// ...
What I need to be able to do is to evict a single cached item. The SubPageType currentPage
is routed through a CMS and can have pretty much any URL depending on the site structure. Default the OutputCache use the URL as a key, I have however not found a way to invalidate items in the OutputCache using the key.
Is it possible to set a Tag dynamically? E.g. having the URL as a tag per page. Or possibly create a custom OutputCacheAttribute where this would be possible and jack that attribute up to the CacheEntry pipeline.
Any help is appreciated.
You can creat a custom DynamicTagCachePolicy
to Override the default policy.
And in CacheRequestAsync method to add the custom tags.
ValueTask IOutputCachePolicy.CacheRequestAsync(OutputCacheContext context,CancellationToken cancellationToken)
{
//...
var route = context.HttpContext.Request.Path.ToString();
var userId = "uid";
var dynamicTag = $"{route}_{userId}";
context.Tags.Add(dynamicTag);
return ValueTask.CompletedTask;
}