2

I have successfully implemented Azure Redis Cache using the Microsoft RedisOutputCacheProvider from NuGet which works as expected for general pages.

[ChildActionOnly]
[ChildActionOutputCache(CacheProfile.StaticQueryStringComponent)]
public ActionResult Show(int id)
{
    // some code
}

However, I can't seem to get it to work for child actions. Prior to using Redis Cache, it was working using the default OutputCacheProvider.

Does anyone have any ideas, or is it simply a limitation?

Thanks in advance

Sam Gooch
  • 131
  • 1
  • 4

1 Answers1

2

In your Global.asax.cs, set a custom child action output cache that talks to Redis:

protected void Application_Start()
{
    // Register Custom Memory Cache for Child Action Method Caching
    OutputCacheAttribute.ChildActionCache = new CustomMemoryCache("My Cache");
}

This cache should derive from MemoryCache and implement the following members:

/// <summary>
/// A Custom MemoryCache Class.
/// </summary>
public class CustomMemoryCache : MemoryCache
{
    public CustomMemoryCache(string name)
        : base(name)
    {

    }
    public override bool Add(string key, object value, DateTimeOffset absoluteExpiration, string regionName = null)
    {
        // Do your custom caching here, in my example I'll use standard Http Caching
        HttpContext.Current.Cache.Add(key, value, null, absoluteExpiration.DateTime,
            System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);

        return true;
    }

    public override object Get(string key, string regionName = null)
    {
        // Do your custom caching here, in my example I'll use standard Http Caching
        return HttpContext.Current.Cache.Get(key);
    }
}

More info on my blog post

Haney
  • 32,775
  • 8
  • 59
  • 68
  • This was a great start for me but the string named key in the Add method of CustomMemoryCache is not the same as the one generated in the Add method in CustomOutputCacheProvider. For example, in CustomMemoryCache, when the Add method is called, the key is generated randomly, in my case the key was DyTdvXwzRuwozPQ4TW4atFVQjGIIO1s850zOBRPKf8s=" where as in CustomOutputProvider's Add method, the string key is generated correctly with "a2/test/authenticatedonly" – Frank Fu Mar 19 '18 at 05:52