我开发了一个 http 处理程序来动态提供图像..
我对每个图像都有各自的最后修改日期。
所以我实现了http头缓存,如下:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
DateTime lastModified = Convert.ToDateTime("2/1/2013 12:00:00 AM");
string eTag = "test.JPG" + lastModified.ToString();
// set cache info
context.Response.Cache.VaryByHeaders["If-Modified-Since"] = true;
context.Response.Cache.VaryByHeaders["If-None-Match"] = true;
context.Response.Cache.SetLastModified(lastModified);
context.Response.Cache.SetETag(eTag);
//Set cache control header
context.Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
Byte[] imageBytes = CreateImage();
context.Response.OutputStream.Write(imageBytes, 0, imageBytes.Length);
}
注意:这里lastModified 将为每个图像动态获取,每个图像的名称也会不同。
响应标头
HTTP/1.1 200 OK
Cache-Control: private
Content-Type: image/jpeg
Last-Modified: Thu, 31 Jan 2013 18:30:00 GMT
Etag: test.JPG2/1/2013 12:00:00 AM
Vary: If-Modified-Since, If-None-Match
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?RTpcTGVhcm5pbmdcQ2FjaGVcR2V0SW1hZ2UuYXNoeA==?=
X-Powered-By: ASP.NET
Date: Mon, 08 Jul 2013 11:22:26 GMT
Content-Length: 384411
请求标头
GET /GetImage.ashx HTTP/1.1
Host: localhost:50432
User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20100101 Firefox/22.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
问题
此页面已正确缓存..但是下次当我加载具有不同 lastModified 值的页面时,这使得 etag 也不同..
但是页面根本没有命中处理程序..它总是显示缓存中的图像......
而且由于它没有击中处理程序,我如何检查 lastModified 值并相应地服务..