【问题标题】:ASP.NET MVC ySlow Add Expires Headers for dynamically served scriptASP.NET MVC ySlow 为动态提供的脚本添加过期标头
【发布时间】:2025-11-25 12:25:01
【问题描述】:

我正在为 Javascript 提供一个如下所示的控制器方法:

  [OutputCache(Duration = 120)]
  [Compress]
  public ActionResult JavascriptFile(String scriptName) {
     string content;
     if (HttpContext.IsDebuggingEnabled) {
        content = ReadApplicationScript(string.Format("~/scripts/{0}", scriptName));
        return Content(content, "application/javascript");
     }
     else {
        content = ReadApplicationScript(string.Format("~/scripts/Built/{0}", scriptName));
        return Content(content, "application/javascript");
     }
  }

Compress 属性来自here

当我运行 ySlow 时,我在“添加过期标题”上获得了 F 级。我该怎么做才能添加这些?

【问题讨论】:

    标签: asp.net-mvc yslow controller-action expires-header


    【解决方案1】:

    在 system.webServer 部分添加以下内容

    <staticContent>
          <clientCache cacheControlMode="UseExpires"
             httpExpires="Tue, 19 Jan 2038 03:14:07 GMT" />
        </staticContent>
    

    这里的 httpExpires 值将是到期日期。

    编辑

    您也可以尝试像这样将内容添加到缓存中:

    var cacheName = "someName";
    var value = HttpRuntime.Cache.Get(cacheName) as ContentResult;
    
                if (value == null)
                {                
                    var contentResult = ReadApplicationScript(string.Format("~/scripts/{0}",scriptName));
                    System.Web.HttpContext.Current.Cache.Insert(cacheName, contentResult );
                    return contentResult;
                }
    
                return value;
    

    【讨论】:

    • 我已经有这个标签了,我认为问题是因为我动态地提供脚本它不是静态内容所以这不适用。
    • 请尝试将内容添加到缓存中。我没有测试代码。
    • @DhavalPanchal ,您可以在 system.webServer 部分下使用 Web.config 中的第一个代码块。如果您正在使用 MVC,则可以创建一个控制器操作以使用第二个代码块返回内容结果。希望这会有所帮助。
    • 我正在使用 ASP.Net,并且我已经在 web.config 中添加了该块。它适用于我的网站的静态内容,但不适用于从第三方脚本添加的参考,例如我的域是:www.abc.com 并且脚本参考是从 www.xyz.com 加载的