Feel like a geek and get yourself Ema Personal Wiki for Android and Windows

10 August 2009

IE, ASP.NET MVC, AJAX and browser caching

IE caches AJAX requests and won't reload the resource by default. Other browsers do it differently. I am not sure who's "right" here (this document may have the answer). But this can be very annoying behaviour in AJAX applications.

The solution is to explicitely tell IE not to cache.

On this website kazimanzurrashid posted an ActionFilterAttribute to control browser caching behaviour. I changed it a bit so it is possible to prevent any browser caching.

I now have an attribute on my base controller class:
[BrowserCache(PreventBrowserCaching=true)]

This prevents any caching by default. This can be overriden if required (which I never do).

The attribute looks like this:

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

namespace YourNameSpaceHere
public class BrowserCacheAttribute : ActionFilterAttribute
{
///
/// Gets or sets the cache duration in seconds.
/// The default is 10 seconds.
///

/// The cache duration in seconds.
public int Duration
{
get;
set;
}

public bool PreventBrowserCaching
{
get;
set;
}

public BrowserCacheAttribute()
{
Duration = 10;
}

public override void OnActionExecuted(
ActionExecutedContext filterContext)
{
if (Duration < 0) return;

HttpCachePolicyBase cache = filterContext.HttpContext
.Response.Cache;

if (PreventBrowserCaching)
{
cache.SetCacheability(HttpCacheability.NoCache);
Duration = 0;
}
else
{
cache.SetCacheability(HttpCacheability.Public);
}

TimeSpan cacheDuration = TimeSpan.FromSeconds(Duration);
cache.SetExpires(DateTime.Now.Add(cacheDuration));
cache.SetMaxAge(cacheDuration);
cache.AppendCacheExtension("must-revalidate,"
+ "proxy-revalidate");
}
}
}

1 comment:

jmcilhinney said...

Many thanks. A quick copy and paste and now my users can't go back if they're not supposed to. Exactly what I needed.