[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


Containerizing #Java Applications in @Azure using DC/OS and the Azure #ContainerService https://t.co/wuRe5z6laW

August 26, 2016 10:21

How to run #Meteor applications on Azure #AppServices https://t.co/nGO8UMI1T6 #JavaScript

August 25, 2016 11:42

What’s New in C# 7.0 <3 https://t.co/CltbhlSXmT

August 25, 2016 11:35

This is the new Microsoft :) Live from #LinuxCon: Sharing the latest news and learnings on #Microsoft’s open journey https://t.co/P8UZUwHHAX

August 23, 2016 07:00

How to create a #Docker Datacenter on Microsoft #Azure https://t.co/dql2jYD0xQ

August 22, 2016 15:00

RT @DockerParis: Notre prochain meetup aura lieu au Palais des Congrès à l'occasion des MS Experiences https://t.co/73ZRAyTiFS

August 22, 2016 14:21

Les sessions de @ContainerDay16 sont en ligne! Ma keynote #Container #Azure / #Windows est ici: https://t.co/DnKgiez1Bk

August 22, 2016 07:04

Provisioning the #Azure #Kubernetes infrastructure with a declarative template https://t.co/yQFOfgzEbR

August 20, 2016 09:58

All you need to know about #Windows #Containers in one pic! https://t.co/p5wcaIZf0R

August 20, 2016 08:39

#DevOps: Build, push and run @Docker images using #VisualStudio Team Services https://t.co/r9KNaZnJ9U https://t.co/DtMagfwjC5

August 19, 2016 13:06

Nice video: Run #PowerShell Natively on #Linux with @Docker :) https://t.co/b8nwA8XbGL

August 19, 2016 06:40

Very cool update: New UI and new navigation for #TeamServices https://t.co/4UFohxPuMA

August 19, 2016 05:38

#PowerShell is now open source and available on #Linux :) https://t.co/HfCYEoSIvz

August 18, 2016 16:37

@fdibot @Azure un outil fait par Docker (un template ARM en fait :)) -> https://t.co/oeoDFPkL7p

August 18, 2016 12:57

First Look: #Docker for @Azure Beta https://t.co/VL1S8Q2csC

August 18, 2016 12:53