Friday 7 June 2013

Disable browser cache in ASP.NET MVC

First you need to create a custom action filter. For that you need to inherit  the class from ActionFilterAttribute.


  public class CustomActionFilterAttribute : ActionFilterAttribute
    {
       public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            var cache = filterContext.HttpContext.Response.Cache;
            cache.SetCacheability(HttpCacheability.NoCache);
            cache.SetRevalidation(HttpCacheRevalidation.ProxyCaches);
            cache.SetExpires(DateTime.Now.AddYears(-5));
            cache.AppendCacheExtension("private");
            cache.AppendCacheExtension("no-cache=Set-Cookie");
            cache.SetProxyMaxAge(TimeSpan.Zero);
        }

    }


To Implement above Action filter to any controller or to any particular action, you need to decorate controller or action as shown below:
   [CustomActionFilter]
    public class DemoController : Controller

    {
        ..Your Code..
    }


In MVC4, to disable browser caching across all controllers, but retain it for anything not served by a controller, add this to FilterConfig.RegisterGlobalFilters:
filters.Add(new  CustomActionFilterAttribute ());

No comments:

Post a Comment