如何在ASP.NET MVC中支持ETag?
答案 0 :(得分:42)
@Elijah Glover's answer是答案的一部分,但并不完全正确。这将设置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
}
答案 1 :(得分:30)