c# - Cache-Control HTTP header 可以正常工作

标签 c# asp.net response cache-control

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

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

最佳答案

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

关于c# - Cache-Control HTTP header 可以正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5394979/

相关文章:

c# - 如何在 C# 中的 NHibernate 的 QueryOver 中使用 Oracle 的内置关键字或函数?

c# - 将文本框绑定(bind)到列表框 SelectedItem

c# - 捆绑和缩小错误

c# - 最小起订量如果方法设置相交会怎样?

c# - 当使用此类时,想要强制执行类的特定方法执行顺序。是否存在针对此的设计模式?

c# - 连接字符串加密,什么意思?

c# - 在 C# Web API Web 服务中使用 Process() 调用 GhostScript

Symfony2 |从响应/转发中隐藏/删除 header

javascript - 发送 ajax 请求和接收响应(同步)

java - 用于 json 的日期格式