Search code examples
asp.net-corecaching.net-corerazorasp.net-core-tag-helpers

Cache tag helper with vary-by-route attribute


I want to use a cache tag helper with vary-by-route attribute but I'm not sure wether my implementation is correct.

My routes are shapped like : http://mywebsite.com/category/job/region/department/city

"category/job/region/department/city" is my path param defined in route's template in Startup.cs :

app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "DB_Pages",
                    template: "{**path}",
                    defaults: new { controller = PathHelper.GetControllerName<PageController>(), action = nameof(PageController.Page) });
      });

I want to cache a menu present on all pages, but the content depends on the url. So I set in my view component output (razor - Default.chtml) :

<cache expires-sliding="@TimeSpan.FromHours(24)" vary-by-route="path">
    <!-- Dynamic Html code -->
</cache>

But when I access twice to the same url, I don't see any difference. I wonder wether the cache is working.

PS: I have app.UseResponseCaching(); in Startup.cs (I'm not sure this is related)


Solution

  • Here is a working demo:

    Startup:

    app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{path?}");
    
                });
    

    View:

    <cache expires-sliding="@TimeSpan.FromHours(24)" vary-by-route="path">
        Current Time Inside Cache Tag Helper: @DateTime.Now
    </cache>
    

    result: enter image description here