Azure Redis Cache and MVC Child Actions

244 Views Asked by At

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

1

There are 1 best solutions below

1
Haney On

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