开发者

Handling Expires Headers in ASP.Net MVC

开发者 https://www.devze.com 2023-02-02 02:56 出处:网络
I need advice or suggestions on how to add Expires Headers to my CSS, Image and JavaScript files in ASP.Net MVC.

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 thoug开发者_如何学编程h..


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


Another, less complicated option is to add a randomized or versioned query string to the end of the file path.

<link rel="stylesheet" type="text/css" href="somecssfile.css?version=1.0.0.3" />

When you change the version, the browser will get a new copy of the file.

0

精彩评论

暂无评论...
验证码 换一张
取 消