asp.net-mvcyslowcontroller-actionexpires-header

ASP.NET MVC ySlow Add Expires Headers for dynamically served script


I am serving Javascript vai a controller method that looks like this:

  [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");
     }
  }

The Compress attribute is from here.

When I run ySlow I get an F grade on "Add Expires headers". What can I do to add these?


Solution

  • Add the following inside system.webServer section

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

    Here the httpExpires value will be the expiration date.

    Edit

    You can also try adding the content to cache like this:

    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;