Search code examples
c#asp.net-core-mvcresponsecache

ASP.NET Core ResponseCacheAttribute - VaryByCustom?


I've been using Microsoft.AspNetCore.Mvc.ResponseCacheAttribute for the first time and have come across an issue that I would have solved previously using the VaryByCustom property in OutputCachein ASP.NET (and using public override string GetVaryByCustomString(HttpContext context, string s) in the global.asax).

This VaryByCustom caching seems to no longer exist in ASP.NET Core. Is there a built-in alternative that I'm missing here or will I need to implement this myself to achieve something similar?


Solution

  • From my understanding, you have two flexible options in ASP.NET core:

    1. Use the VaryByHeader or VaryByQueryKeys if you're using the ResponseCacheAttribute.

    When using Headers, you need to write the value to vary by as a header, which could be any arbitrary value (no need to expose data to the client):

    Response.Headers.Add("X-My-Vary-Header", "this-is-variable");
    

    In essence, this is all the VaryByCustomString ever did for you anyway. The way I see it, you're no longer forced to put this code in a specific method/file (e.g. global.asax).

    1. Try the <cache> Tag Helper when caching in Razor.

    Here you have a wide range of things to "vary" by: vary-by-header, vary-by-route, vary-by-user, and even a custom vary-by.

    Have a look here and decide whether to use the attribute or the cache tag helper: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/cache-tag-helper