其實這個也是新瓶裝舊酒的問題,前段時間,把這個做了,況且效果和效能都還不錯,所以記錄下,希望能協助更多的人
雖然 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 也終於能智能點了,不過,還是沒有想到更加方便的對頁面片段進行依賴緩衝了
其實這個也是新瓶裝舊酒的問題,前段時間,把這個做了,況且效果和效能都還不錯,所以記錄下,希望能協助更多的人
雖然 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 也終於能智能點了,不過,還是沒有想到更加方便的對頁面片段進行依賴緩衝了