'ASP.NET MVC 5 Cache CSS and JS Files
I am using ASP.NET MVC 5. My goal is to cache CSS and JS files for at least 24 hours. I tried this code with no luck:
https://docs.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/clientcache
I added this code, but I still see no caching:
public class MvcApplication : HttpApplication
{
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpContext.Current.Response.Headers.Remove("X-Powered-By");
HttpContext.Current.Response.Headers.Remove("X-AspNet-Version");
HttpContext.Current.Response.Headers.Remove("X-AspNetMvc-Version");
HttpContext.Current.Response.Headers.Remove("Server");
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.SuppressXFrameOptionsHeader = true;
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl);
HttpContext.Current.Response.Headers.Set("Cache-Control", "private, max-age=31536000");
}
}
Result:
GET http://localhost:51000/content/assets/css/colors.min.css HTTP/1.1 Host: localhost:51000 Connection: keep-alive Pragma: no-cache Cache-Control: no-cache User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36 Accept: text/css,/;q=0.1
Solution 1:[1]
In your web.config
file, add
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="1:00:00"/>
</staticContent>
under system.webServer
section.
cacheControlMaxAge format is "DAY:HOUR:SECOND" .
It's working for me. Hopefully it's help you.
Solution 2:[2]
You can do this in the startup for most modern sites in c#. The below will add a cache for js, css and fonts.
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = context =>
{
var cachePeriod = "10600";
if (!context.File.Name.EndsWith(".js") &&
!context.File.Name.EndsWith(".css") &&
!context.File.Name.EndsWith(".woff"))
return;
context.Context.Response.Headers.Append("Cache-Control", $"public,max-age={cachePeriod}");
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ashiquzzaman |
Solution 2 | Aaron Gibson |