I have a single-page JavaScript application, held within an ASP.NET MVC 3 website.
In order to cache-bust the JS/CSS files used by the application, without the need for manually renaming files each time a change is made, I have the following routes & respective controller actions for serving static files.
Global.asax.cs
routes.MapRoute(
"AppCssFile",
"style.{version}.min.css",
new { controller = "StaticFile", action = "CssFile" }
);
routes.MapRoute(
"AppJsFile",
"app.{version}.min.js",
new { controller = "StaticFile", action = "JsFile" }
);
StaticFileController
//NB: m_JsAppFolder references below just point to the root folder for static files
[HttpGet]
public FileResult CssFile()
{
var sourceFile = HttpContext.Server.MapPath(Path.Combine(m_JsAppFolder, "assets", "style", "release.css"));
return new FilePathResult(sourceFile, "text/css");
}
[HttpGet]
public FileResult JsFile()
{
var sourceFile = HttpContext.Server.MapPath(Path.Combine(m_JsAppFolder, "release.js"));
return new FilePathResult(sourceFile, "text/javascript");
}
This works well, however the problem is that my Cache-Control header does not return the value I would expect…
As I have the following in my Web.config:
...
<urlCompression doStaticCompression="true" />
<staticContent>
<!-- Set expire headers to 1 year for static content-->
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
<!-- use utf-8 encoding for anything served text/plain or text/html -->
<remove fileExtension=".css" />
<mimeMap fileExtension=".css" mimeType="text/css" />
<remove fileExtension=".js" />
<mimeMap fileExtension=".js" mimeType="text/javascript" />
</staticContent>
...
I would expect to see a Cache-Control header of Cache-Control:public,max-age=31536000, in the same as if the CSS/JS files were referenced directly, rather than via a Controller Action.
Is there anyway to get MVC to treat a controller action response as staticContent: I don’t really want to have to manually set the Cache-Control header in my controller, as this would mean that both this setting and that in the Web.config could get out of sync.
Are you looking for the OutputCacheAttribute?
With this you can have your result cache in the server and the client using the properties Duration and Location.