How to Leverage Browser Caching with Ektron

  • Updated

This article demonstrates a sample of how to leverage .NET browser caching in the context of Ektron.

The sample below is an implementation of an HTTP module which adds an expiry at the end of every request.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


namespace Ektron.Com.HttpModules
{
    /// 
    /// Summary description for ExpiresHeaders
    /// 
    public class ExpiresHeaders : IHttpModule
    {
        private HttpApplication _context;
        private string[] expireExts = { ".png", ".ico", ".jpg", ".css", ".js", "gif" };

        void context_EndRequest(object sender, EventArgs e)
        {
            bool addExpires = false;
            string path = _context.Request.Url.AbsolutePath.ToLower();
            if (!path.Contains("workarea/") && (!path.Contains(".javascript.ashx") && !path.Contains(".stylesheet.ashx")))
            {
                for (int i = 0; i < expireExts.Length; i++)
                {
                    if (path.EndsWith(expireExts[i]))
                    {
                        addExpires = true;
                        break;
                    }
                }
            }
            if (addExpires)
            {
                _context.Response.ExpiresAbsolute = DateTime.Now.AddDays(7);
            }
        }

        public void Dispose() { }

        public void Init(HttpApplication context)
        {
            _context = context;
            _context.EndRequest += new EventHandler(context_EndRequest);
        }
    }
}

Place the class similar to the above into the app_code/cscode folder structure (create your own folder in that place if you haven't) and configure it in the web.config. In the web.config, look for the node under and add a line like this (but using the namespace and class name from your own class): 

 
<add name="ExpiresHeaders" type="Ektron.Com.HttpModules.ExpiresHeaders" preCondition="integratedMode">

Please NOTE the following:

The code above is more about .NET and little to do with Ektron.  When trying to solve performance problems with HTTP modules care is needed because if done incorrectly can cause their own performance reasons.  Make sure the code within these is executed only when necessary and is as efficient as possible.