每个用户输出缓存

CR4*_*G14 11 c# asp.net-mvc-3

嗨有一个相当大的内存密集的仪表板,每个用户是不同的.如何根据当前登录的userID缓存响应,该userID不作为参数传递,但需要从当前登录的用户派生.我的理解是VaryByParam查看请求上下文

此外,数据库中还有一个值,当更改此值时,需要重置缓存

hai*_*770 27

在你的Web.config:

<caching>
  <outputCacheSettings>
    <outputCacheProfiles>
      <add name="Dashboard" duration="86400" varyByParam="*" varyByCustom="User" location="Server" />
    </outputCacheProfiles>
  </outputCacheSettings>
</caching>
Run Code Online (Sandbox Code Playgroud)

在你的Controller/ Action:

[OutputCache(CacheProfile="Dashboard")]
public class DashboardController : Controller { ...}
Run Code Online (Sandbox Code Playgroud)

然后在你的Global.asax:

    //string arg filled with the value of "varyByCustom" in your web.config
    public override string GetVaryByCustomString(HttpContext context, string arg)
    {
        if (arg == "User")
        {
            // depends on your authentication mechanism
            return "User=" + context.User.Identity.Name;
            //?return "User=" + context.Session.SessionID;
        }

        return base.GetVaryByCustomString(context, arg);
    }
Run Code Online (Sandbox Code Playgroud)

实质上,GetVaryByCustomString将让您编写一个自定义方法来确定是否存在Cache hit/ miss返回一个字符串,该字符串将用作每个Cache副本的某种"哈希".