ASP. NET MVC 5 Кэш CSS и JS Файлы - PullRequest
0 голосов
/ 23 февраля 2020

Я использую 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 Хост: localhost: 51000 Соединение: keep-alive Прагма: без кэширования Cache-Control: без кэширования User-Agent: Mozilla / 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit / 537.36 (K HTML) , как у Gecko) Chrome / 79.0.3945.130 Safari / 537.36 Принять: текст / css, / ; q = 0.1

1 Ответ

0 голосов
/ 24 февраля 2020

В вашем файле web.config добавьте

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

в секцию system.webServer.

cacheControlMaxAge формат "ДЕНЬ: ЧАС: ВТОРОЙ ".

Это работает для меня. Надеюсь, это поможет вам.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...