[EN] [ASP.NET MVC] Custom output cache provider

September 13, 2011 -

Since ASP.NET 4 was released it’s possible to write custom output cache providers to change the way data are cached. For example, one of my customer wanted that some actions were cached on the file system to avoid loss of cache during an application pool reboot.

Be careful by using the following code because in many scenarios it can’t be used “as it is” (in a web farm, for example).

A custom output cache provider is a simple class that inherits from OutputCacheProvider and overrides these methods :

  • Add : adds an entry in the cache
  • Get : gets an entry from the cache
  • Remove : removes an entry from the cache
  • Set : updates an entry in the cache

Cached items must be serializable. In this sample, the following class will be used :

[Serializable]
public class CachedItem
{
    public object Item { get; set; }
    public DateTime UtcExpiry { get; set; }
}

In order to save an item on the file system the two following methods will be used. The first allows to get a file path from the cache key (generated by asp.net) and the second allows to save a CachedItem on the disk :

private string GetFilePathFromKey(string key)
{
    foreach (var invalidChar in Path.GetInvalidFileNameChars())
        key = key.Replace(invalidChar, '_');

    return Path.Combine(CacheDirectory, key);
}

private void SaveCachedItem(CachedItem cachedItem, string filePath)
{
    if (File.Exists(filePath))
        File.Delete(filePath);

    using (var stream = File.OpenWrite(filePath))
    {
        var binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(stream, cachedItem);
    }
}

The Add method :

public override object Add(string key, object entry, DateTime utcExpiry)
{
    string filePath = GetFilePathFromKey(key);
    var cachedItem = GetCachedItem(filePath);

    if (cachedItem != null && cachedItem.UtcExpiry.ToUniversalTime() <= DateTime.UtcNow)
    {
        Remove(key);
    }
    else if (cachedItem != null)
    {
        return cachedItem.Item;
    }

    SaveCachedItem(new CachedItem()
    {
        Item = entry,
        UtcExpiry = utcExpiry
    }, filePath);

    return entry;
}

The Get method :

public override object Get(string key)
{
    string filePath = GetFilePathFromKey(key);
    var cachedItem = GetCachedItem(filePath);
    if (cachedItem != null)
    {
        if (cachedItem.UtcExpiry.ToUniversalTime() <= DateTime.UtcNow)
        {
            Remove(key);
        }
        else
        {
            return cachedItem.Item;
        }
    }

    return null;
}

The Remove method :

public override void Remove(string key)
{
    string filePath = GetFilePathFromKey(key);
    if (File.Exists(filePath))
        File.Delete(filePath);
}

The Set Method :

public override void Set(string key, object entry, DateTime utcExpiry) {
    string filePath = GetFilePathFromKey(key);
    var cachedItem = new CachedItem() {Item = entry, UtcExpiry = utcExpiry};
    SaveCachedItem(cachedItem, filePath);
}

Now that the output cache provider is created, it can be registered in the web.config file of the application, in the caching section :

<system.web>
<caching>
  <outputCache>
    <providers>
      <add name="FileSystemOutputCacheProvider"
           type="Samples.FileSystemOutputCacheProvider, Samples"/>
    </providers>
  </outputCache>
</caching>

The last step consists to override the GetOutputCacheProviderName method in the Global.asax file. Actually this method is called by the ASP.NET Framework when an OutputCache attribute (or an OutputCache directive) is used. The method returns the name of the output cache provider to use in the current context. For example, if you want to use the FileSystemOutputCacheProvider for the Details action of the Products controller, you can use this code :

public override string GetOutputCacheProviderName(HttpContext context)
{
    if (context.Request.RawUrl.ToUpper().Contains("PRODUCTS/DETAILS")) {
        return "FileSystemOutputCacheProvider";
    }
    return base.GetOutputCacheProviderName(context);
}

As mentioned previously you just have to set an OutputCache attribute on the action Details of the Products controller to use the custom output cache provider :

public class ProductsController : Controller
{
    [OutputCache(Duration = 3600, VaryByParam = "id")]
    public ActionResult Details(int id)
    {
        //long operation
        Thread.Sleep(2000);

        ViewBag.ProductId = id;
        return View();
    }
}

Download the source code here.

Hope this helps Winking smile

Comments

Share

Tags


Twitter


Profile and Time your #ASPNET MVC app all the way to #Azure - http://t.co/0jwINoQc76

July 30, 2014 07:21

How to create a file with a . dot prefix in Windows Explorer - http://t.co/8OrilUEp0d

July 30, 2014 07:01

Protecting an MVC4 VS2012 Project with OpenId Connect and #Azure AD - http://t.co/y7oSwK912o

July 29, 2014 16:28

Using the #Azure File Service in your Cloud Services (Web and Worker Roles) http://t.co/e7NizgOXMu

July 29, 2014 15:16

How to Host Multiple #Cloud Business Apps on the Same #Azure #WebSite - http://t.co/l3TlmPinGp

July 29, 2014 13:17

Setting up #Azure #ActiveDirectory and #ASPNET Single Sign On - http://t.co/fYil76cVjq

July 29, 2014 12:01

Expanding #OpenSource technologies on #Windows - http://t.co/5ZpY0v08pD

July 29, 2014 09:54

Writing Mobile Applications? What are your Options? - http://t.co/KIvFlB5SnW

July 29, 2014 08:37

Microsoft #SQL Replication Between Windows #Azure Virtual Machines - http://t.co/QpPWAawjrk

July 29, 2014 07:21

More Updates to #Azure Mobile Services (Link) - http://t.co/ocMVuowRED

July 29, 2014 07:01

Fitbit is the first fitness band to support Windows Phone | The Verge http://t.co/jmxxzTI4HP

July 28, 2014 18:51

How to break the locked lease of #blob storage in Windows #Azure - http://t.co/P4Yg6Fwx1a

July 28, 2014 12:01

#Azure Automation: Integrating Runbook Source Control using Visual Studio Online #VSO http://t.co/okHeYfE3Vc

July 27, 2014 13:17

Success with hybrid #cloud : http://t.co/ss4jV82qdC

July 27, 2014 12:01

RT @JamesvandenBerg: #Microsoft Datacenter Infrastructure and Management datasheet : http://t.co/XQyKWhEgin #sysctr #Azure #WS2012R2 #Cloud

July 27, 2014 11:38