【问题标题】:ASP.NET MVC 5 Cache CSS and JS FilesASP.NET MVC 5 缓存 CSS 和 JS 文件
【发布时间】:2020-06-07 12:13:07
【问题描述】:

我正在使用 ASP.NET MVC 5。我的目标是缓存 CSS 和 JS 文件至少 24 小时。我试过这段代码没有运气:

https://docs.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");
        }
    }

结果:

GET http://localhost:51000/content/assets/css/colors.min.css HTTP/1.1 主机:本地主机:51000 连接:保持活动 Pragma:无缓存 缓存控制:无缓存 用户代理:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36 接受:text/css,/;q=0.1

【问题讨论】:

    标签: css asp.net-mvc


    【解决方案1】:

    在您的 web.config 文件中,添加

    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="1:00:00"/>
    </staticContent>
    

    system.webServer 部分下。

    cacheControlMaxAge 格式为 "DAY:HOUR:SECOND"

    它对我有用。希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 2014-05-28
      • 1970-01-01
      • 2012-08-13
      • 1970-01-01
      • 2017-05-14
      • 1970-01-01
      • 2011-11-01
      • 1970-01-01
      相关资源
      最近更新 更多