题
我如何支持的ETag在ASP.NET MVC?
解决方案
@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
}
不隶属于 StackOverflow