Bilal Fazlani
Bilal Fazlani

Reputation: 6977

asp.net mvc : Images,Css files & javascript files are not being cached

I din't want my pages to be cached for security and for consistency. When I hit back button on browser, it should always go to server to get the html.

I achieved it by creating the following actionfilter.

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);
    }
}

I applied to filter to to everything as a global filter

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        // Makes sure that cached pages are not served to any browser including chrome
        filters.Add(new NoCache());
    }

The problem was solved. But now all Images, css and javascript files are also not being cached. How I tell it to cache them?

Upvotes: 2

Views: 2361

Answers (1)

Bhushan Firake
Bhushan Firake

Reputation: 9458

You may try enabling cache in your web.config:

The <clientCache> element of the <staticContent> element specifies cache-related HTTP headers that Internet Information Services (IIS) sends to Web clients, which control how Web clients and proxy servers will cache the content that IIS returns.

For example, the httpExpires attribute specifies a date and time that the content should expire, and IIS will add an HTTP "Expires" header to the response. The value for the httpExpires attribute must be a fully-formatted date and time that follows the specification in RFC 1123. For example:

<configuration>
   <system.webServer>
      <staticContent>
         <clientCache cacheControlMode="UseExpires"
            httpExpires="Tue, 19 Jan 2038 03:14:07 GMT" />
      </staticContent>
   </system.webServer>
</configuration>

You can refer this link for more info.

Upvotes: 2

Related Questions