缓存由http处理程序提供的动态图像

Jam*_*mes 5 .net asp.net caching httphandler http-headers

我已经开发了一个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);
    }
Run Code Online (Sandbox Code Playgroud)

注意:这里 将为每个图像动态获取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
Run Code Online (Sandbox Code Playgroud)

请求标题

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
Run Code Online (Sandbox Code Playgroud)

这个页面正在被正确缓存.但是下次我加载具有不同lastModified值的页面时,这使得etag也不同...

但页面根本没有击中处理程序..它始终显示缓存中的图像...

因为它没有击中处理程序,我如何检查lastModified值并相应地提供服务..