How to use Tag with [OutputCache] on Controllers instead of Minimal API's

429 views Asked by At

We can use Tag like that with Minimal API's .CacheOutput(x=x.Tag("people")); So that we can use IOutputCacheStore.EvictByTag("people");.

But when it comes to controllers, we have to use [CacheOutput] attribute which does not have 'Tag'. There is no such usage like [CacheOutput(Tag="people)] so that I can not use EvictByTag(). I don't want to migrate all my controllers to minimal API's. Is there a way to use Tag with controllers?

3

There are 3 answers

0
Guru Stron On

CacheOutput builds cache policy which is applied to particular mapped endpoint. You can declare policy when adding services for output cache and pass policy name to the attribute:

builder.Services.AddOutputCache(options =>
    options.AddPolicy("PeopleTagPolicy", policyBuilder => policyBuilder.Tag("people")));

[OutputCache(PolicyName = "PeopleTagPolicy")]
public class PeopleController : ControllerBase
{

}
0
Igor Samoylenko On

Try to use HttpContext.Features

HttpContext.Features.Get<IOutputCacheFeature>()?.Context.Tags.Add("you tag");
0
Mark Lagendijk On

This was added in .NET 8, so you now can do:

[OutputCache(Tags = ["people"])]