2009-06-02 124 views

回答

41

@Elijah Glover的答案的一部分答案,但并不完全。这将设置ETag,但是如果不在服务器端检查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 
} 
30

MVC中的ETAG与WebForms或HttpHandlers相同。

您需要一种创建ETAG值的方法,我发现的最好方法是使用文件MD5或ShortGuid

由于.NET接受字符串作为一个ETAG,你可以将它轻松地使用

String etag = GetETagValue(); //e.g. "00amyWGct0y_ze4lIsj2Mw" 
Response.Cache.SetETag(etag); 

视频从MIX,最后他们使用ETAG与REST

+2

我认为这是错误的!因为添加静态ETag就好像说你的内容永远不会改变。 ETags的想法是让浏览器知道内容已经改变,类似于到期头文件。 – 2012-10-15 13:35:43

+6

我认为编码值仅用于说明目的...您可以随时创建并更改它。 – Romias 2012-10-15 14:06:33

相关问题