Search code examples
c#asp.net-coreresponsecache

Asp.net core 2.2 response caching, cannot add must-revalidate to cache-control response header


I am using following setup for response caching:

 services.AddMvc(options =>
            {
                
                options.CacheProfiles.Add("HomePage", new CacheProfile()
                {
                    Duration = Constants.HomePageOutputCacheInSeconds,
                    Location = ResponseCacheLocation.Any,
                    VaryByHeader = HttpCacheProfileProvider.CacheKeyHeader

                });
                options.CacheProfiles.Add("Article", new CacheProfile()
                {
                    Duration = Constants.ArticleOutputCacheInSeconds,
                    Location = ResponseCacheLocation.Any,
                    VaryByHeader = HttpCacheProfileProvider.CacheKeyHeader
                });
                options.CacheProfiles.Add("Default", new CacheProfile()
                {
                    Duration = Constants.DefaultOutputCacheInSeconds,
                    Location = ResponseCacheLocation.Any,
                    VaryByHeader = HttpCacheProfileProvider.CacheKeyHeader
                });

                


            }).SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2);

services.AddMemoryCache();
services.AddResponseCaching();

And in configure section I set:

 app.UseResponseCaching();

And controller:

[Route("", Name = "DesktopHome")]
[ResponseCache(CacheProfileName = "HomePage", Order = int.MaxValue)]
public async Task<IActionResult> Index()

Everything works well. Cache-Control:public, max-age:10 is appended in the headers, but I would like to set must-revalidate and max-stale-cache properties as well, and I cant find property to acomplish that.

Property is not available in the CacheProfiles setup, ResponseCacheAttribute, nor in the app.UseResponseCaching setup.

Is that possible?


Solution

  • Besides set in Cacheprofile, you can directly use Response to set them in action:

        public async Task<IActionResult> Index()
        {
            Response.GetTypedHeaders().CacheControl = new CacheControlHeaderValue()
            {
                Public = true,
                MaxAge = TimeSpan.FromSeconds(600),
                MustRevalidate = true,
                MaxStale = true
            };
    
            return View();
        }
    

    enter image description here

    Or you can check Response Caching Middleware in official site.