如何在 ASP.NET MVC 中支持 ETag?
问问题
25652 次
2 回答
46
@Elijah Glover 的答案是答案的一部分,但并不完整。这将设置 ETag,但如果不在服务器端进行检查,您将无法获得 ETag 的好处。你这样做:
var requestedETag = Request.Headers["If-None-Match"];
if (requestedETag == eTagOfContentToBeReturned)
return new HttpStatusCodeResult(HttpStatusCode.NotModified);
另外,另一个提示是您需要设置响应的可缓存性,否则默认情况下它是“私有的”并且不会在响应中设置 ETag:
Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
所以一个完整的例子:
public ActionResult Test304(string input)
{
var requestedETag = Request.Headers["If-None-Match"];
var responseETag = LookupEtagFromInput(input); // lookup or generate etag however you want
if (requestedETag == responseETag)
return new HttpStatusCodeResult(HttpStatusCode.NotModified);
Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
Response.Cache.SetETag(responseETag);
return GetResponse(input); // do whatever work you need to obtain the result
}
于 2013-07-15T16:08:07.000 回答