asp.net-mvc 如何在 ASP.NET MVC 中支持 ETag?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/937668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I support ETags in ASP.NET MVC?
提问by Patrick Gidich
How do I support ETags in ASP.NET MVC?
如何在 ASP.NET MVC 中支持 ETag?
采纳答案by jaminto
@Elijah Glover's answeris part of the answer, but not really complete. This will set the ETag, but you're not getting the benefits of ETags without checking it on the server side. You do that with:
@Elijah Glover 的回答是答案的一部分,但并不完整。这将设置 ETag,但如果不在服务器端检查它,您将无法获得 ETag 的好处。你这样做:
var requestedETag = Request.Headers["If-None-Match"];
if (requestedETag == eTagOfContentToBeReturned)
return new HttpStatusCodeResult(HttpStatusCode.NotModified);
Also, another tip is that you need to set the cacheability of the response, otherwise by default it's "private" and the ETag won't be set in the response:
此外,另一个提示是您需要设置响应的可缓存性,否则默认情况下它是“私有的”并且不会在响应中设置 ETag:
Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
So a full example:
所以一个完整的例子:
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
}
回答by Elijah Glover
ETAG's in MVC are the same as WebForms or HttpHandlers.
MVC 中的 ETAG 与 WebForms 或 HttpHandlers 相同。
You need a way of creating the ETAG value, the best way I have found is using a File MD5 or ShortGuid.
您需要一种创建 ETAG 值的方法,我发现的最佳方法是使用 File MD5 或ShortGuid。
Since .net accepts a string as a ETAG, you can set it easily using
由于 .net 接受字符串作为 ETAG,您可以使用
String etag = GetETagValue(); //e.g. "00amyWGct0y_ze4lIsj2Mw"
Response.Cache.SetETag(etag);
Video from MIX, at the end they use ETAG's with REST
来自MIX 的视频,最后他们将 ETAG 与 REST 结合使用

