Search code examples
outputcache

.net 7 How to set outputcache expiration from inside the controller?


I need to set the Cache Duration within the controller or set something that can be used by a cache policy to set the ResponseExpirationTimeSpan. (How long the data can be cached varies based on the situation)

I am not using minimal API.

I tried setting the expiry value via httpContext and picking it up in a policy. eg. HttpContext.Items["cacheExpire"] = 2;

but

IOutputCachePolicy.CacheRequestAsync & IOutputCachePolicy.ServeFromCacheAsync gets called before the controller method and setting it in IOutputCachePolicy.ServeResponseAsync does not take effect.

What is the correct solution for this scenario?


Solution

  • To set the cache duration in a controller, get the IOutputCacheFeature and set the time on it.

    example:

    public class TestController: ControllerBase
    {
      [HttpGet]
      public ActionResult<string> Get()
      {
         var cache = HttpContext.Features.Get<IOutputCacheFeature>() ?? throw new InvalidOperationException("Output cache feature not found");
         cache.Context.ResponseExpirationTimeSpan = TimeSpan.FromSeconds(20);
         return "Test Controller";
      }
    }