Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Expires Headers in ASP.Net MVC

Tags:

asp.net

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..

like image 214
Damien Avatar asked Dec 29 '10 10:12

Damien


2 Answers

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>
like image 66
Wiebe Tijsma Avatar answered Oct 08 '22 19:10

Wiebe Tijsma


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

like image 34
Spencer Ruport Avatar answered Oct 08 '22 20:10

Spencer Ruport