Search code examples
c#asp.netasp.net-mvccachinghttpcontext

Set no cache in ASP.NET for specific page?


I would like to set my MVC 5 application to not cache the page for my Login view (i.e. I would like the Login view to actually reload if my user has pressed 'Back' in the browser in order to navigate to the Login page).

This is so that I can log the current user out before the user attempts to log in as somebody else.

I saw an example of somebody using this in Global.asax:

protected void Application_BeginRequest()
{
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Cache.SetExpires(DateTime.Now.AddDays(-1));
    Response.Cache.SetNoStore();
    Response.Cache.SetProxyMaxAge(new TimeSpan(0, 0, 0));
    Response.Cache.SetValidUntilExpires(false);
    Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
}

but this stops caching for basically every page on every request. I believe there is a way to do this through routing or filters? Maybe a method annotation? Can anybody explain this?


Solution

  • Why don't you add these attributes to your action:

    [OutputCacheAttribute(VaryByParam = "*", Duration = 0, NoStore = true)] 
    

    Example:

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