Showing posts with label Cache. Show all posts
Showing posts with label Cache. Show all posts

Saturday, September 8, 2012

Disable Caching for a Controller Action in ASP.NET MVC

At times, we need to disable the caching for some controller actions in our MVC application.
Say for example, there is an "Add Entry" link on your view, and it has a controller action assigned to it.
Clicking on this "Add Entry" link should call an action, and that will eventually load an Entry fill-up screen/ dialog.
Now when user clicks it for the first time it will call the controller action fine. But for next consecutive clicks, it may or may not call controller action and due to which the target dialog/ entry screen will remain prefilled with old data.
This is because of caching. Under some circumstances, browser caches controller actions, and that is why the cached operation is performed rather than the controller action.

To deal with this problem, we need to disable caching of those controller actions. (Its always recommended to disable caching of controller actions that invoke Add/ Edit of entry).

Following is the walkthrough to achieve the same:

1. Create an action filter. To do that create a new class inherited  ActionFilterAttribute class.

public
class NoCache : 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);
   
}
}

2. Decorate your controller action with the action filter class.

[NoCache]
public ActionResult EditEntry(int entryId)
{
..... the controller action code.}

This is what we need to do to disable caching of controller action in ASP.NET  MVC.