如何在ASP.NET MVC中支持ETag?

时间:2009-06-02 02:22:23

标签: asp.net-mvc etag

如何在ASP.NET MVC中支持ETag?

2 个答案:

答案 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)

MVC中的ETAG与WebForms或HttpHandlers相同。

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

由于.net接受一个字符串作为ETAG,您可以使用

轻松设置它
String etag = GetETagValue(); //e.g. "00amyWGct0y_ze4lIsj2Mw"
Response.Cache.SetETag(etag);

来自MIX的视频,最后他们使用带有REST的ETAG