OutPutCache 自定义缓存:session、登录用户、cookie 等

其实这个也是新瓶装旧酒的问题,前段时间,把这个做了,况且效果和性能都还不错,所以记录下,希望能帮助更多的人

虽然 outputcache 很重要,但是这个功能真的不好用,很多时间不能满足需求,比如做一些自定义方面的缓存依赖,如:session、登录用户信息、用户cookie信息 等,更重要的是,想做片段缓存的话,就只能用 用户控件了,并且这是时,用户控件之间的传值就比较难了,所以,让人很不爽!真怀疑,asp.net 的开发工程师是不是就不用 asp.net,开发出来的产品,离实用还是有段距离的吧!!!!

好了,还得自己动手,解决了 一些自定义方面的需求,支持 session、登录用户、cookie 等,代码如下:
以下代码只是测试,如果使用,请按自己需求更改部分代码。

Global.asax 文件里面加入此方法:

 

    protected void Application_BeginRequest(Object sender, EventArgs e)
{
//solove "vary" outputcache bug
Response.Cache.SetOmitVaryStar(true);

//exclude mobile browser
string acceptTypes = Request.Headers["Accept"];
if (!string.IsNullOrEmpty(acceptTypes) && acceptTypes.ToLower().Contains("text/vnd.wap.wml"))
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
}

public override string GetVaryByCustomString(HttpContext context, string arg)
{
string key=string.Empty;
arg = arg.ToLower();

//outputcache customer
if (arg.Contains("user")) //Login User
{
key +="user:"+ HttpContext.Current.User.Identity.Name +";";
}

if (arg.Contains("admin")) // Is Admin User
{
key +="admin:"+ HttpContext.Current.User.Identity.Name +";-";
}

if (arg.Contains("hot")) //Is HotRate List
{
HttpCookie cookie = Request.Cookies["hot"];
bool isHotRate =true;
if (cookie !=null&& cookie.Value =="0")
isHotRate =false;

key +="hot:"+ isHotRate.ToString() +";";
}

if (arg.Contains("login")) //User Is Login
{
key +="login:"+ context.User.Identity.IsAuthenticated.ToString() +";";
}

return key;
}



 

之后在调用页面头部加入下面代码,也就是在 VaryByParam 里面自定义依赖项:

<% @ OutputCache Duration = " 10 " VaryByParam = " id;pagenum " VaryByCustom = " Admin;Login " %>



这个页面的缓存依赖将会是:contentid(id,url中的参数)、pagenum(pagenum,url中的参数)、Admin(是否是管理员,自定义的依赖)和Login(用户是否登录,自定义的依赖)

好了,这样就能比较完美的支持 session、登录用户、cookie 等自定义依赖缓存了,outputcache 也终于能智能点了,不过,还是没有想到更加方便的对页面片段进行依赖缓存了

转载于:https://www.cnblogs.com/xunziji/archive/2011/07/11/2103257.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值