jam*_*nto 44
@Elijah Glover的答案是答案的一部分,但并不完全正确.这将设置ETag,但是如果不在服务器端检查它,你就无法获得ETag的好处.你这样做:
var requestedETag = Request.Headers["If-None-Match"];
if (requestedETag == eTagOfContentToBeReturned)
return new HttpStatusCodeResult(HttpStatusCode.NotModified);
Run Code Online (Sandbox Code Playgroud)
此外,另一个提示是您需要设置响应的可缓存性,否则默认情况下它是"私有",并且不会在响应中设置ETag:
Response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
Run Code Online (Sandbox Code Playgroud)
这是一个完整的例子:
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
}
Run Code Online (Sandbox Code Playgroud)
Eli*_*ver 30
MVC中的ETAG与WebForms或HttpHandlers相同.
您需要一种创建ETAG值的方法,我发现使用File MD5或ShortGuid的最佳方法.
由于.net接受一个字符串作为ETAG,您可以使用它轻松设置它
String etag = GetETagValue(); //e.g. "00amyWGct0y_ze4lIsj2Mw"
Response.Cache.SetETag(etag);
Run Code Online (Sandbox Code Playgroud)
来自MIX的视频,最后他们使用ETAG和REST
| 归档时间: |
|
| 查看次数: |
23111 次 |
| 最近记录: |