【问题标题】:Caching ASHX Image Response缓存 ASHX 图像响应
【发布时间】:2011-11-25 11:42:06
【问题描述】:

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

网址:

~/image.ashx?dir=user&w=25&h=25&force=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 的多个调用上吗?任何提示将不胜感激。

【问题讨论】:

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


    【解决方案1】:

    当然是这一行:

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

    应该是:

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

    【讨论】:

    • @SubinJacob - 这些是缓存头。你在说什么?
    • 如果用户更改了内容(图像),我想让缓存过期
    • @SubinJacob - 那为什么不问一个新问题呢?
    猜你喜欢
    • 2015-02-27
    • 2020-01-18
    • 2018-08-05
    • 1970-01-01
    • 2019-03-12
    • 2019-05-31
    • 1970-01-01
    • 2010-11-19
    • 2020-10-08
    相关资源
    最近更新 更多