缓存ASHX图像响应

时间:2011-09-26 19:23:49

标签: c# caching image-processing asp.net-4.0 ashx

我已经创建了一个ashx文件来动态生成图像缩略图。我想在第一次调用这些图像后将其缓存在客户端。

URL:

  

〜/ image.ashx DIR =用户安培; W = 25安培; H = 25安培;力= YES&安培; IMG = matt.jpg

代码背后:

public void ProcessRequest (HttpContext context) {
    TimeSpan refresh = new TimeSpan(0, 15, 0);
    context.Response.Cache.SetExpires(DateTime.Now.Add(refresh));
    context.Response.Cache.SetMaxAge(refresh);
    context.Response.Cache.SetCacheability(HttpCacheability.Server);
    context.Response.CacheControl = HttpCacheability.Public.ToString();
    context.Response.Cache.SetValidUntilExpires(true);

    string dir = context.Request.QueryString["dir"];
    string img = context.Request.QueryString["img"];
    bool force = context.Request.QueryString["force"] == "yes";
    double w = 0;
    double h = 0;
    ...
    context.Response.ContentType = "image/jpeg";
    thumb.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}

使用Chrome中的开发工具我可以看到以下响应标题:

HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Mon, 26 Sep 2011 19:17:31 GMT
X-AspNet-Version: 4.0.30319
Set-Cookie: .ASPXAUTH=...; path=/; HttpOnly
Cache-Control: no-cache
Pragma: no-cache
Expires: -1
Content-Type: image/jpeg
Content-Length: 902
Connection: Close

有人可以告诉我为什么这不是使用相同的URL进行多次调用的缓存吗?任何提示将不胜感激。

1 个答案:

答案 0 :(得分:5)

当然这一行:

HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Server);

应该是:

HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);