我如何支持的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
}

其他提示

ETAG在MVC中的相同的WebForms或HttpHandlers的。

您需要创建ETAG值的一种方式,我已经找到了最好的方法是使用一个文件MD5或的 shortGuid

由于.NET接受字符串作为一个ETAG,可以容易地设定它使用

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

MIX 时,在端部,他们使用ETAG与REST

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top