I need advice or suggestions on how to add Expires Headers to my CSS, Image and JavaScript files in ASP.Net MVC.
A key issue is that the software is not in a single location. It is distributed to clients who handle the hosting so I would rather have a solution that doesn't require manual configration in IIS unless it's unavoidable!
I googled around and the majority of answers seem to be focused on content that is returned via a controller. Can't do that for JavaScript files though..
Which IIS Version are you using?
If by 'manual IIS configuration' you mean having to open the IIS manager console, IIS 7.5 (and I think 7 as well) allows you to add expires headers to static content using only the web.config:
<system.webServer>
  <staticContent>
    <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:30:00" />
  </staticContent>
</system.webServer>
                        You can do something like this by writing a custom handler for your javascript files. In your Web.Config file of your MVC project look for the httpHandlers section. Add something like the following line:
<add verb="GET" path="/YourScriptsFolder/*.js" type="Your.Project.Namespace.And.Custom.Handler, Your.Assembly.Name" validate="false" />
This will force all requests for js files in that folder through your custom handler which will look something like this:
class CustomHandler : IHttpHandler 
{
    #region IHttpHandler Members
    public bool IsReusable
    {
        get { return true; }
    }
    public void ProcessRequest(HttpContext context)
    {
        // Set any headers you like here.
        context.Response.Expires = 0; 
        context.Response.Cache.SetExpires(DateTime.Parse("3:00:00PM")); 
        context.Response.CacheControl="no-cache"; 
        // Determine the script file being requested.
        string path = context.Request.ServerVariables["PATH_INFO"];
        // Prevent the user from requesting other types of files through this handler.
        if(System.Text.RegularExpressions.RegEx.Match(path, @"/YourScriptsFolder/[^/\\\.]*\.js"))
            context.Response.Write(System.IO.File.ReadAllText(path));
    }
    #endregion
}
I haven't tested this code so you might run into some issues but this is the basic idea. There are a plethora of examples on ASP.Net custom handlers throughout the web. Here's a good example:
http://www.developer.com/net/asp/article.php/3565541/Use-Custom-HTTP-Handlers-in-Your-ASPNET-Applications.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With