Processing Expires Headers in ASP.Net MVC

I need tips or suggestions on adding Expires headers to my CSS, image and JavaScript files in ASP.Net MVC.

The key problem is that the software is not in one place. It is distributed among clients who handle hosting, so I would prefer to have a solution that does not require manual configuration in IIS, if this is not inevitable!

I googled around, and most of the answers seem to focus on content that comes back through the controller. There is no way to do this for JavaScript files though ..

+4
source share
3 answers

You can do something like this by writing a custom handler for your javascript files. In the Web.Config file of your MVC project, find 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 this 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 have not tested this code so you might run into some problems, but this is the main idea. There are many examples of ASP.Net custom handlers all over the Internet. Here is a good example:

http://www.developer.com/net/asp/article.php/3565541/Use-Custom-HTTP-Handlers-in-Your-ASPNET-Applications.htm

+3
source

What version of IIS are you using?

If by “manual IIS configuration” you mean opening the IIS manager console, IIS 7.5 (and, it seems to me, 7), you can add headers to static content using only web.config:

 <system.webServer> <staticContent> <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:30:00" /> </staticContent> </system.webServer> 
+5
source

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 the version is changed, the browser will receive a new copy of the file.

0
source

Source: https://habr.com/ru/post/1333655/


All Articles