加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – MVC3自定义输出缓存

发布时间:2020-12-16 03:37:16 所属栏目:asp.Net 来源:网络整理
导读:我想在我的应用程序中使用缓存,但我返回的数据特定于登录用户.当我需要因用户而异时,我无法使用任何现成的缓存规则. 有人可以指出我在创建自定义缓存属性方面的正确方向.从控制器我可以从Thread.CurrentPrincipal.Identity访问用户;或者我在控制器构造函数_u
我想在我的应用程序中使用缓存,但我返回的数据特定于登录用户.当我需要因用户而异时,我无法使用任何现成的缓存规则.

有人可以指出我在创建自定义缓存属性方面的正确方向.从控制器我可以从Thread.CurrentPrincipal.Identity访问用户;或者我在控制器构造函数_user中初始化的私有控制器成员

谢谢.

解决方法

你可以使用VaryByCustom.在Global.asax中重写GetVaryByCustomString方法:

public override string GetVaryByCustomString(HttpContext context,string arg)
{
    if (arg == "IsLoggedIn")
    {
         if (context.Request.Cookies["anon"] != null)
         {
              if (context.Request.Cookies["anon"].Value == "false")
              {
                   return "auth";
              }
              else
              {
                   return "anon";
              }
          }
          else
          {
             return "anon";
          }
    }
    else
    {
        return base.GetVaryByCustomString(context,arg);
    }
}

然后使用OutputCache属性:

[OutputCache(CacheProfile = "MyProfile")]
public ActionResult Index()
{
   return View();
}

并在web.config中:

<caching> 
    <outputcachesettings>             
        <outputcacheprofiles> 
            <clear /> 
            <add varybycustom="IsLoggedIn" varybyparam="*" duration="86400" name="MyProfile" /> 
        </outputcacheprofiles> 
    </outputcachesettings> 
</caching>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读