2011-03-15 103 views
15

我試圖實現功能來緩存某些頁面,具體取決於主機。這是因爲我可以擁有多個具有相同參數的頁面版本,並且請求方面的唯一區別在於請求的主機。如何實現VaryByCustom緩存?

因此,例如這兩個網址會要求相同的頁面,但他們的風格是不同的:

http://www.a.com/something/specific 

http://www.b.com/something/specific 

我要通過這裏列出的例子:

http://msdn.microsoft.com/en-us/library/5ecf4420%28v=VS.90%29.aspx

但它是沒有意義的 我。

我已經添加到了我的Global.asax:

public override string GetVaryByCustomString(HttpContext context, string arg) 
{ 
    if (arg == "host") 
    { 
     return "host=" + context.Request.Url.Host; 
    } 

    return base.GetVaryByCustomString(context, arg); 
} 

和示例國家「以編程方式設置自定義字符串,調用SetVaryByCustom方法,並把它傳遞給使用自定義字符串」,使用代碼類似於以下內容:

Response.Cache.SetVaryByCustom("host"); 

問題是我不知道如何處理這個。我已將上一行添加到MvcApplication_EndRequest,因爲它似乎有意義,但我認爲這是不正確的,因爲當我在GetVaryByCustomString中設置斷點時,它們永遠不會被擊中。

有人可以告訴我我在這裏失蹤了嗎?或者如果我需要以不同的方式做這件事?

編輯:

[CustomOutputCache(CacheProfile = "FundScreener")] // or similar depending on the action 

其中CustomOutputCacheAttribute被定義爲:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 
public class CustomOutputCacheAttribute: OutputCacheAttribute 
{ 
    public override void OnResultExecuted(ResultExecutedContext filterContext) 
    { 
     AddLabelFilesDependency(filterContext); 
     base.OnResultExecuted(filterContext); 
    } 

    private static void AddLabelFilesDependency(ControllerContext filterContext) 
    { 
     IConfigurationManager configurationManager = ObjectFactory.TryGetInstance<IConfigurationManager>(); 
     if (configurationManager == null 
      || filterContext == null 
      || filterContext.RequestContext == null 
      || filterContext.RequestContext.HttpContext == null 
      || filterContext.RequestContext.HttpContext.Response == null 
      ) 
     { 
      return; 
     } 
     string[] files = Directory.GetFiles(configurationManager.LabelsDirectoryPath, "*.xml"); 
     foreach(var file in files) 
     { 
      filterContext.RequestContext.HttpContext.Response.AddFileDependency(file); 
     } 
    } 
} 

其中簡檔被定義爲:

下面
RE Darin的答案,我已經與裝飾我的行動
<add name="FundScreener" 
    location="Server" 
    enabled="true" 
    varyByParam="*" 
    duration="1200" 
    sqlDependency="mmftms:offline.ScreenerData"/> 

我需要更改嗎?

回答

7

您不需要在MVC中調用SetVaryByCustom。您可以使用OutputCache屬性。結帳following blog post

+0

嗨達林,謝謝你的回答。我仍然有點困惑。我已經更新了更具體的問題。 – DaveDev 2011-03-15 15:32:59

+1

...實際上,隨着我進一步閱讀,我可以看到該示例包含'varybycustom =「IsLoggedIn」'。這可能是我需要的! - 感謝 – DaveDev 2011-03-15 15:34:05

+0

這個伎倆..只是要注意,雖然該屬性是區分大小寫,所以它實際上'varyByCustom =「主機」' – DaveDev 2011-03-15 16:15:37

3

GetVaryByCustomString(...)由緩存層根據請求調用,並且您有機會檢查請求和傳入的參數以決定如何「分類」此請求。因此,如果您將VaryByCustom屬性/屬性設置爲「主機」,那麼您將在GetVaryByCustomString函數中編寫代碼,該函數返回主機(如上例所示)。如果緩存層發現它已經使用返回的值緩存了參數「host」,那麼它將返回緩存的響應,否則它會執行請求並將其添加到緩存中。

0

根據您的編輯,將VaryByCustom="host"添加到您的FundScreener輸出緩存配置文件。

4

如果你希望有不同的主機不同的緩存,您可以使用:

VaryByHeader =「主機」

因爲,這將使它在請求中使用的標題「主機」的價值改變緩存。您可以在控制器/操作的OutputCache指令中添加它,或者可以在web.config中全局指定它。

如果您使用主機綁定,主機頭將始終存在,這似乎是您的情況。