在编写自定义 IHttpHandler 时,我遇到了一种与 HttpCachePolicy 对象有关的行为,这是我没有预料到的。
我的处理程序计算并设置一个实体标签(使用与当前响应对象关联的 HttpCachePolicy 上的 SetETag 方法)。如果我使用 SetCacheability 方法将缓存控制设置为 public,一切都会像魅力一样工作,并且服务器会发送 e-tag header 。如果我将其设置为私有(private),电子标签 header 将被抑制。
也许我只是看得不够仔细,但我在 HTTP/1.1 规范中没有看到任何可以证明这种行为合理的内容。为什么您不想向浏览器发送 E-Tag,同时仍然禁止代理存储数据?
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext ctx) {
ctx.Response.Cache.SetCacheability(HttpCacheability.Private);
ctx.Response.Cache.SetETag("\"static\"");
ctx.Response.ContentType = "text/plain";
ctx.Response.Write("Hello World");
}
public bool IsReusable { get { return true; } }
}
会回来
Cache-Control: private Content-Type: text/plain; charset=utf-8 Content-Length: 11
But if we change it to public it'll return
Cache-Control: public Content-Type: text/plain; charset=utf-8 Content-Length: 11 Etag: "static"
I've run this on the ASP.NET development server and IIS6 so far with the same results. Also I'm unable to explicitly set the ETag using
Response.AppendHeader("ETag", "static")
更新:在 IIS7 中运行时可以手动附加 ETag header ,我怀疑这是由于 ASP.NET 和 IIS7 管道之间的紧密集成造成的。
澄清:这是一个很长的问题,但核心问题是:为什么 ASP.NET 会这样做,我应该如何绕过它?
更新:我要接受 Tony's answer因为它本质上是正确的(去托尼!)。我发现,如果您想完全模拟 HttpCacheability.Private,您可以将可缓存性设置为 ServerAndPrivate,但您也有调用缓存。 SetOmitVaryStar (true) 否则缓存会将 Vary: * header 添加到输出中,而您不希望这样。当我获得编辑权限时,我会把它编辑到答案中(或者如果你看到这个托尼,也许你可以编辑你的答案以包括那个电话?)
最佳答案
我认为你需要使用 HttpCacheability.ServerAndPrivate
这应该在 header 中为您提供 cache-control: private 并让您设置 ETag。
这方面的文档需要改进一些。
编辑: Markus 发现您还调用了 cache.SetOmitVaryStar(true),否则缓存会将 Vary: * header 添加到输出中,而您不希望这样。
关于c# - 为什么 HttpCacheability.Private 会抑制 ETag?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32824/