【问题标题】:Static File Browser Caching for ASP.NET Web Forms ApplicationASP.NET Web 窗体应用程序的静态文件浏览器缓存
【发布时间】:2016-09-26 21:06:57
【问题描述】:

我们希望浏览器缓存网站上某些文件夹(图像/样式/脚本)的内容,并将它们设置为 7 天保持新鲜。此外,我们使用名为 Ektron 的 CMS。

这是我们正在使用的代码,有什么想法为什么它不起作用?

来自 global.asax

void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
    System.Web.HttpCacheability cachelevel = System.Web.HttpCacheability.Private;

    if (Request.FilePath.ToLower().StartsWith("/images") || Request.FilePath.ToLower().StartsWith("/styles") || 
        Request.FilePath.ToLower().StartsWith("/js") || Request.FilePath.ToLower().StartsWith("/scripts"))
    {
        cachelevel = System.Web.HttpCacheability.Public;

        if (cachelevel == System.Web.HttpCacheability.Public) Response.Cache.SetCacheability(cachelevel);

        var staticExtensions = new List<string> { ".js", ".css", ".jpg", ".gif", ".png" };

        if (staticExtensions.Any(ext => Request.FilePath.ToLower().EndsWith(ext)))
        {
            Response.Cache.SetMaxAge(TimeSpan.FromDays(7));
        }
    }

【问题讨论】:

  • 怎么不工作了?
  • 内容没有被缓存,头部没有区别,一切仍然设置为 maxage=0 并且缓存控制是私有的。我认为它应该设置为公开且最大年龄=604800。

标签: c# asp.net caching iis global-asax


【解决方案1】:

不要认为 Application_PreSendRequestHeaders 不会针对每个静态内容触发。 而是使用 Web.config system.webServer - staticContent - clientCache 设置,如下所示:

<system.webServer>
 <staticContent>
  <clientCache cacheControlMaxAge="7.00:00:00" cacheControlMode="UseMaxAge" />
 </staticContent>

这会将其设置为 7 天

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-28
    • 2019-09-21
    • 2010-10-31
    • 2020-08-03
    • 1970-01-01
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多