Umbraco and Donut Output Cache

0
1494

Donut Output Caching is a type of output caching where certain parts of a web page are not cached. It’s a simple way of boosting your site performance!

ASP.NET doesn’t provide a native way of donut output caching, so we must resort to a great NuGet package called MVCDonutCaching. You can read all about it here: http://www.devtrends.co.uk/blog/donut-output-caching-in-asp.net-mvc-3.

Since Umbraco is built on top of ASP.NET MVC, we can easily use this package on our websites. There are, however, some caveats, because Umbraco doesn’t use the native MVC routing.

For Umbraco, every page that uses the same document type is processed through the same route, therefore, if we have 100 news articles that use the NewsItem document type, from the moment we open one news article page, every other news item page will display the same information, despite having a different URL!

The way to bypass this issue is the following:

Create a Global.cs file that includes the logic to cache a page based on their url and not the document type

namespace CreateIT.Web
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Umbraco.Web;

    public class Global : UmbracoApplication
    {
        public override string GetVaryByCustomString(HttpContext context, string custom)
        {
            if (custom.ToLower() == "url")
            {
                return "url=" + context.Request.Url.AbsoluteUri;
            }

            return base.GetVaryByCustomString(context, custom);
        }
    }
}

Then, instruct Umbraco to use this class when launching the UmbracoApplication by changing the Global.asax file:

<%@ Application Codebehind="Global.cs" Inherits="CreateIT.Web.Global" Language="C#" %>

Finally, setup an Output Cache profile in your Web.config:

<system.web>
    (...)
    <caching>
      <outputCacheSettings>
        <outputCacheProfiles>
          <add enabled="true" name="CreateIT.Actions" duration="900" location="Server" varyByCustom="url" varyByParam="*" />
        </outputCacheProfiles>
      </outputCacheSettings>
    </caching>
</system.web>

And decorate the chosen controllers (that you used to hijack the Umbraco routes) with the Donut Output Cache attribute:

[DonutOutputCache(CacheProfile = "CreateIT.Actions")]
public class HomepageController : Umbraco.Web.Mvc.RenderMvcController
{

If you wish to exclude a certain part of your page from the cache, just create a Surface Controller action that returns a partial view and use the extension method provided by MVCDonutCaching for @Html.Action().

LEAVE A REPLY

Please enter your comment!
Please enter your name here