2011-03-22 81 views
2

我遇到了緩存控制問題。我有一個具有多個主機頭的IIS網站。當您瀏覽網站編號1時,將爲此網站設置緩存,當您再次打開瀏覽器並轉到第二個網站時,您將看到來自第一個網站的內容。如何根據網站用戶訪問來確定緩存內容?當你有1個網站和主機標題與SAME網站相關時,一切工作正常。緩存控制HTTP頭確實正常工作

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

回答

2

聽起來像是你應該主機頭值添加到您的IsClientCached算法

+0

您要求添加Request.Header.Add(「主機」,「www.host.com」);然後使用這個值來檢查?如果你看看ETag方法,你會發現我們基於數據庫值生成etag,所以etag是唯一的。這就是爲什麼我很困惑。 etag是獨一無二的,它爲什麼要緩存它?我做了一些研究,發現一篇文章提到標記是特定於站點的,它沒有任何意義 – agassan 2011-03-22 18:50:37

+1

瀏覽器應該已經在發送主機報頭。我在說你需要將主機頭值作爲你的緩存「鑰匙」的一部分。 – 2011-03-23 13:46:59