我如何支持ASP.NET MVC的ETag? [英] How do I support ETags in ASP.NET MVC?

查看:520
本文介绍了我如何支持ASP.NET MVC的ETag?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何支持ETag的在ASP.NET MVC?

How do I support ETags in ASP.NET MVC?

推荐答案

@Elijah Glover的答案是答案的一部分,但没有真正完成。这将设置ETag的,但你不能没有检查它在服务器端获得的ETag的好处。你这样做有:

@Elijah Glover's answer is 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:

var requestedETag = Request.Headers["If-None-Match"];
if (requestedETag == eTagOfContentToBeReturned)
        return new HttpStatusCodeResult(HttpStatusCode.NotModified);

此外,另一个技巧是,你需要设置响应的缓存能力,否则默认情况下它是私人和ETag的不会响应进行设置:

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:

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
}

这篇关于我如何支持ASP.NET MVC的ETag?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆