[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


@InfoAbonneCanal Ça remarche, merci sauf la case à cocher pour retenir la conf. il faut remettre les sous titres à chaque épisode...

January 17, 2017 20:12

Hey bsr @InfoAbonneCanal, FYI depuis 3 jours, plus de sous titres sur la vost de l'application TV connectées​ Samsung ! Merci :-)

January 16, 2017 19:58

A Different Approach To #Test Your @ASPNET Core Application https://t.co/9kjb6NsG1t #dotnet #dotnetcore

January 13, 2017 17:07

Just found this task to generate a release not file at build time using #vsts and #tfs - really cool ! https://t.co/P5tBdRJRnM

January 13, 2017 15:17

RT @brendandburns: The state of Kubernetes in Azure Container Service https://t.co/eruqgVk35l And we're already working on polishing thos…

January 11, 2017 22:26

RT @docker_fr: RT: #Meetup @DockerParis 17/01 chez @venteprivee_fr@benjguin parle comparaison de sol. streaming #bigdata avec https://t.c

January 11, 2017 19:39

CI/CD with #Azure #Container Service and #Docker #Swarm https://t.co/C6ZtoaVNW7 #DevOps #VSTS

January 11, 2017 19:37

RT @rgardler: How to integrate a new Azure Container Service cluster into an existing virtual network using ACS Engine https://t.co/Sxk4h2q…

January 11, 2017 19:35

How to integrate a new @Azure #ContainerService cluster into an existing virtual network using #ACSEnginehttps://t.co/nxRqeVbgcC

January 10, 2017 14:10

RT @fdibot: Envie de comprendre pourquoi @Docker c'est le présent et l'avenir ? venez écouter @jcorioland, @wiboconsulting et moi même au #

January 10, 2017 09:20

#containerd - Core Container Runtime Project For The container Industry https://t.co/1czRFQwcLo

January 05, 2017 08:38

Deprecation of the Team Rooms in #TeamServices and #TFS https://t.co/w2I0tiXqQ7

January 05, 2017 08:02

#Docker Logs API Format Explained https://t.co/0AZEtalRiR

January 05, 2017 07:52

End-to-end cloud #experiences for developers at #Nodejs Interactive North America https://t.co/b8Nbte3i96

January 04, 2017 11:46

Should You Go ‘#Serverless’? The Pros and Cons https://t.co/dvxflKwT5f #Cloud #Architecture

January 03, 2017 08:40