2012-10-14 25 views
1

我在我的控制器動作之上定義了OutputCache屬性,以便服務器可以快速地爲不同的用戶提供相同的響應。它緩存了整個整個頁面。我的意思是母版頁也被緩存,如果我緩存了一個返回View()的操作。因此,主頁頂部的用戶帳戶信息會被每個用戶共享。我只想緩存內容頁面,而不是主頁面_Layout.cshtml。我怎樣才能排除這一點?服務器上的OutputCache

編輯: 在那裏我有麻煩的部分是這樣的:

@if(Request.IsAuthenticated) { 
    <text>Hello <strong>@User.Identity.Name</strong>!</text> 
    @: | 
    @Html.ActionLink("Index", "Index", "Account") 
    @: | 
    @Html.ActionLink("Logout", "Logout", "Account") 
} 
else 
{ 
    @:| 
    @Html.ActionLink("Login", "Login", "Account") 
} 

當我緩存控制器動作,返回的視圖也攜帶該用戶登陸部分從緩存中,所以它給出錯誤的禮炮,以幾乎每個用戶。即使頁面被緩存,我如何動態生成這個部分?

回答

2

VaryByCustom是你想要的。

把這個在您的Global.asax:

public override string GetVaryByCustomString(HttpContext context, string custom) 
{ 
    return "User".Equals(custom, StringComparison.OrdinalIgnoreCase) 
     ? User.Identity.Name 
     : base.GetVaryByCustomString(context, custom); 
} 

...然後使用[OutputCache(VaryByCustom = "User")]屬性。

這仍然會導致整個頁面被分開緩存,但會爲每個用戶創建一個單獨的緩存。

如果您正在尋找其他選項,請搜索MVC甜甜圈緩存或MVC甜甜圈空洞緩存。

回覆評論

聽起來像是你想甜甜圈洞緩存。看看this answer可以幫助你。

+0

謝謝,我需要動態生成登錄部分,但要緩存任何用戶的主要內容。 – Halo