首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Cache-Control HTTP标头是否正常工作

Cache-Control HTTP标头是否正常工作
EN

Stack Overflow用户
提问于 2011-03-23 00:59:23
回答 1查看 1.8K关注 0票数 2

我在缓存控制方面遇到了问题。我有一个具有多个主机头的IIS网站。当您浏览站点编号1时,将为此站点设置缓存,当您再次打开浏览器并转到第二个站点时,您将看到来自第一个站点的内容。如何根据网站用户访问量确定缓存内容?当您有1个站点和主机标题与同一站点相关时,一切工作正常。

代码语言:javascript
复制
//Set Cacheability
if (!Context.User.Identity.IsAuthenticated && _activeNode.CacheDuration > 0)
{
    var eTag = GetETag(_activeNode);
    HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
    if (IsClientCached(_activeNode.UpdateTimestamp))
    {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.NotModified;
        HttpContext.Current.Response.SuppressContent = true;
        HttpContext.Current.Response.End();
        return;
    }

    var incomingEtag = HttpContext.Current.Request.Headers["If-None-Match"];
    if (String.Compare(incomingEtag, eTag) == 0)
    {
        HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.NotModified;
        HttpContext.Current.Response.SuppressContent = true;
        HttpContext.Current.Response.End();
        return;
    }

    HttpContext.Current.Response.Cache.SetExpires(DateTime.Now.ToUniversalTime().AddMinutes(_activeNode.CacheDuration));
    HttpContext.Current.Response.Cache.SetMaxAge(new TimeSpan(0, _activeNode.CacheDuration, 0));
    HttpContext.Current.Response.Cache.SetLastModified(_activeNode.UpdateTimestamp);
    HttpContext.Current.Response.Cache.SetETag(eTag);
}

/// <summary>
/// Gets the ETag.
/// </summary>
/// <param name="node">The node.</param>
/// <returns></returns>
private static string GetETag(Node node)
{
    var etag = String.Format("{0}_{1}", node.Site.Id, node.Id);
    return "\"" + Encryption.StringToMD5Hash(etag).Replace("-", null) + "\"";
}

/// <summary>
/// Determines whether [is client cached] [the specified content modified].
/// </summary>
/// <param name="contentModified">The content modified.</param>
/// <returns>
///     <c>true</c> if [is client cached] [the specified content modified]; otherwise, <c>false</c>.
/// </returns>
private bool IsClientCached(DateTime contentModified)
{
    var header = Request.Headers["If-Modified-Since"];
    if (header != null)
    {
        DateTime isModifiedSince;
        if (DateTime.TryParse(header, out isModifiedSince))
        {
            return isModifiedSince > contentModified;
        }
    }

    return false;
}
EN

回答 1

Stack Overflow用户

发布于 2011-03-23 01:26:02

听起来您应该将主机标头值添加到IsClientCached算法中

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5394979

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档