文件时间戳在 IIS 中自动检查,浏览器总是根据时间戳向服务器请求更新文件,因此 .nocache。文件在 IIS 中不需要任何特殊的东西。
但是,如果您希望浏览器缓存 .cache。文件,然后以下 HttpModule 将缓存到期日期设置为从现在起 30 天,用于以 .cache.js 或 .cache.html(或任何扩展名)结尾的文件。浏览器甚至不会请求这些文件的更新版本。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace CacheModulePlayground
{
public class CacheModule : IHttpModule
{
private HttpApplication _context;
public void Init(HttpApplication context)
{
_context = context;
context.PreSendRequestHeaders += context_PreSendRequestHeaders;
}
void context_PreSendRequestHeaders(object sender, EventArgs e)
{
if (_context.Response.StatusCode == 200 || _context.Response.StatusCode == 304)
{
var path = _context.Request.Path;
var dotPos = path.LastIndexOf('.');
if (dotPos > 5)
{
var preExt = path.Substring(dotPos - 6, 7);
if (preExt == ".cache.")
{
_context.Response.Cache.SetExpires(DateTime.UtcNow.Add(TimeSpan.FromDays(30)));
}
}
}
}
public void Dispose()
{
_context = null;
}
}
}
用于此的 web.config 是:
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<system.webServer>
<modules>
<add name="cacheExtension" type="CacheModulePlayground.CacheModule"/>
</modules>
</system.webServer>
</configuration>