enamrik
enamrik

Reputation: 2312

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

Like the question says, I wanted to know if it's possible to turn off caching on all controllers and actions for my entire site. Thanks!

Upvotes: 9

Views: 10920

Answers (4)

Peter Morris
Peter Morris

Reputation: 23264

In web.config you can add additional headers to go out with every response

<configuration>
    <system.webServer>
        <httpProtocol>
          <customHeaders>
            <add name="Cache-control" value="no-cache"/>
          </customHeaders>
        </httpProtocol>
    </system.webServer>
</configuration>

Upvotes: 1

lyubeto
lyubeto

Reputation: 123

You should add this method to your Global.asax.cs file

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            Response.AddHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            Response.AddHeader("Pragma", "no-cache"); // HTTP 1.0.
            Response.AddHeader("Expires", "0"); // Proxies.
        }

This disables cache on every request (images, html, js etc.).

Upvotes: 5

user596075
user596075

Reputation:

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.

Upvotes: 15

Adam Tuliper
Adam Tuliper

Reputation: 30152

Yes, depending on the approach you take. I like applying the actions to a base controller (hence my reply there). You could implement the filter at the link below and implement it as a global filter as well (registered in your global.asax.cs)

Disable browser cache for entire ASP.NET website

Upvotes: 1

Related Questions