我正在使用ASP。NET MVC 5。我的目标是缓存CSS和JS文件至少24小时。我尝试了这个代码,但没有运气:
https://learn.microsoft.com/en-us/iis/configuration/system.webserver/staticcontent/clientcache
我添加了这个代码,但我仍然没有看到缓存:
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");
}
}
结果:
得到http://localhost:51000/content/assets/css/colors.min.cssHTTP://1.1主机:localhost:51000连接:保持活动Pragma:没有缓存缓存控制:无缓存用户代理:Mozilla/5.0(Windows NT 10.0;Win64;x64(AppleWebKit/537.36(KHTML,类似Gecko(Chrome/79.03945.130 Safari/537.36接受:text/css,/;q=0.1
在web.config
文件中,添加
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="1:00:00"/>
</staticContent>
在CCD_ 2部分下。
cacheControlMaxAge格式为"DAY:HOUR:SECOND">。
它对我有用。希望它能帮助你。
您可以在c#中大多数现代站点的启动中执行此操作。下面将为js、css和字体添加一个缓存。
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}");
}
});