Prevent Caching in ASP.NET MVC for Specific Actions Using an Attribute

Prevent Caching in ASP.NET MVC for specific actions using an attribute

To ensure that JQuery isn't caching the results, on your ajax methods, put the following:

$.ajax({
cache: false
//rest of your ajax setup
});

Or to prevent caching in MVC, we created our own attribute, you could do the same. Here's our code:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();

base.OnResultExecuting(filterContext);
}
}

Then just decorate your controller with [NoCache]. OR to do it for all you could just put the attribute on the class of the base class that you inherit your controllers from (if you have one) like we have here:

[NoCache]
public class ControllerBase : Controller, IControllerBase

You can also decorate some of the actions with this attribute if you need them to be non-cacheable, instead of decorating the whole controller.

If your class or action didn't have NoCache when it was rendered in your browser and you want to check it's working, remember that after compiling the changes you need to do a "hard refresh" (Ctrl+F5) in your browser. Until you do so, your browser will keep the old cached version, and won't refresh it with a "normal refresh" (F5).

Prevent Caching of Attributes in ASP.NET MVC, force Attribute Execution every time an Action is Executed

Look at the source code for the AuthorizeAttribute (on Codeplex or via Reflector) to see how it goes about turning off caching for authorized pages. I refactored it into a separate method on my custom authorization attribute which derives from AuthorizeAttribute.

protected void CacheValidateHandler( HttpContext context, object data, ref HttpValidationStatus validationStatus )
{
validationStatus = OnCacheAuthorization( new HttpContextWrapper( context ) );
}

protected void SetCachePolicy( AuthorizationContext filterContext )
{
// ** IMPORTANT **
// Since we're performing authorization at the action level, the authorization code runs
// after the output caching module. In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later be served the
// cached page. We work around this by telling proxies not to cache the sensitive page,
// then we hook our custom authorization code into the caching mechanism so that we have
// the final say on whether a page should be served from the cache.
HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */);
}

ASP.NET MVC how to disable automatic caching option?

You can use the OutputCacheAttribute to control server and/or browser caching for specific actions or all actions in a controller.

Disable for all actions in a controller

[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)] // will be applied to all actions in MyController, unless those actions override with their own decoration
public class MyController : Controller
{
// ...
}

Disable for a specific action:

public class MyController : Controller
{
[OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)] // will disable caching for Index only
public ActionResult Index()
{
return View();
}
}

If you want to apply a default caching strategy to all actions in all controllers, you can add a global action filter by editing your global.asax.cs and looking for the RegisterGlobalFilters method. This method is added in the default MVC application project template.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new OutputCacheAttribute
{
VaryByParam = "*",
Duration = 0,
NoStore = true,
});
// the rest of your global filters here
}

This will cause it to apply the OutputCacheAttribute specified above to every action, which will disable server and browser caching. You should still be able to override this no-cache by adding OutputCacheAttribute to specific actions and controllers.

Disabling caching for MVC Controller Action

You can use the [OutputCache] filter:

[HttpGet]
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public ActionResult Index()
{
// ....
return View();
}

See MSDN

MVC Controller Attribute, are these cached? Attribute constructor only called once?

Try setting the following in you OnActionExecuting to prevent caching:

filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();

Prevent Caching in ASP.NET MVC for specific actions using an attribute

However, according to

Authorize Attribute Lifecycle

ASP.NET will cache ActionFilter attributes. So you may not be able to call the constructor more than once and will instead will have to refactor your code for maintaining the attribute state.

Update

You may be able to controll this by setting the cache policy:

protected void SetCachePolicy( AuthorizationContext filterContext )
{
HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge( new TimeSpan( 0 ) );
cachePolicy.AddValidationCallback( CacheValidateHandler, null /* data */);
}

Prevent Caching of Attributes in ASP.NET MVC, force Attribute Execution every time an Action is Executed

How do I turn off caching for my entire ASP.NET MVC 3 website?

Create a Global Action Filter and override OnResultExecuting():

public class DisableCache : ActionFilterAttribute
{
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
filterContext.HttpContext.Response.Cache.SetNoStore();
}
}

And then register this in your global.asax, like so:

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new DisableCache());
}

In summation, what this does is create a Global Action Filter so that implicitly this will be applied to all Controllers and all Actions.

How to stop MVC caching the results of invoking an action method?

MVC doesn't cache the results. IE does.

So you have to tell IE not to do it.

Here's how I do it. First, an attribute:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public sealed class CacheControlAttribute : ActionFilterAttribute
{
public CacheControlAttribute(HttpCacheability cacheability)
{
this._cacheability = cacheability;
}

public HttpCacheability Cacheability { get { return this._cacheability; } }

private HttpCacheability _cacheability;

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
HttpCachePolicyBase cache = filterContext.HttpContext.Response.Cache;
cache.SetCacheability(_cacheability);
}
}

Next, an action:

    [CacheControl(HttpCacheability.NoCache), HttpGet]
public JsonResult MyAction()


Related Topics



Leave a reply



Submit