【问题标题】:Cache-Control HTTP header does work properlyCache-Control HTTP 标头工作正常
【发布时间】:2011-07-20 16:20:01
【问题描述】:

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

//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;
}

【问题讨论】:

    标签: c# asp.net response cache-control


    【解决方案1】:

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

    【讨论】:

    • 您要求添加 Request.Header.Add("Host", "www.host.com");然后用这个值来检查?如果您查看 ETag 方法,您会发现我们根据数据库值生成 etag,因此 etag 是唯一的。这就是为什么我如此困惑。当 etag 是唯一的时,为什么要缓存它?我做了一些研究,发现一篇文章提到该标签是特定于站点的,这没有任何意义
    • 浏览器应该已经在发送主机头了。我是说您需要将主机标头值作为缓存“键”的一部分。
    猜你喜欢
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 2015-04-08
    • 2015-04-13
    • 1970-01-01
    相关资源
    最近更新 更多