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

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

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

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

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

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/hjtdlx/p/2231169.html