针对不同的Cookie做页面缓存
有時(shí)我們需要為PC瀏覽器及移動瀏覽器生成不同的頁面,為了提高性能,不能每次請求都去判斷User-Agent,通常用一個(gè) Cookie 標(biāo)記一下客戶端是否是移動客戶端,這樣只需要讀取這個(gè) Cookie 的值就知道這個(gè)請求是否是移動端。
這里主要通過 OutputCacheByCustom 來實(shí)現(xiàn)對不同的 Cookie 值生成不同的頁面,具體做法也比較簡單:
1. 在 Global.asmx.cs 里重寫 GetVaryByCustomString 函數(shù)
這個(gè)函數(shù)接受兩個(gè)參數(shù),第一個(gè)是 System.Web.HttpContext 對象,包含了對話的上下文,第二個(gè)是 string 類型的,用戶判斷具體采用用戶定義的哪種緩存方案。
public override string GetVaryByCustomString(System.Web.HttpContext context, string custom) {if (custom == "IsMobile"){if (context.Request.Cookies["IsMobile"] == null)return string.Empty;return context.Request.Cookies["IsMobile"].Value;}else{return base.GetVaryByCustomString(context, custom);} }2. 在需要判斷 Cookie 生成不同緩存的 View 上添加 OutputCache Attribute
public class CacheController : Controller {[OutputCache(Duration=60, VaryByCustom="IsMobile",Location=OutputCacheLocation.Server)]public ActionResult Index(){return Content(DateTime.Now.ToString());} }以上兩步就可以了,當(dāng)然也可以將緩存方案寫進(jìn) Web.config 配置文件中:
<system.web><caching><outputCacheSettings><outputCacheProfiles><clear /><!-- 60 seconds--><add varyByCustom="IsMobile" duration="60" name="ChangeByDevice" location="Server" /></outputCacheProfiles></outputCacheSettings></caching> </system.web>在 View 相應(yīng)的位置只需指定 OutputCache 的 CacheProfile
public class CacheController : Controller {[OutputCache(CacheProfile = "ChangeByDevice")]public ActionResult Index(){return Content(DateTime.Now.ToString());} }測試
打開 http://localhost/cache/index
Output:2014/10/26 13:58:01
在控制臺修改 IsMobile 的 Cookie 值
var date = new Date(); var expireDays = 100; date.setTime(date.getTime() + expireDays*24*3600*1000); document.cookie = "isMobile=1; path=/; expires=" + date.toGMTString();重寫打開 http://localhost/cache/index
Output:2014/10/26 13:58:16
轉(zhuǎn)載于:https://www.cnblogs.com/technology/p/4051933.html
總結(jié)
以上是生活随笔為你收集整理的针对不同的Cookie做页面缓存的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 记一次Linux修改MySQL配置不生效
- 下一篇: Java 内存模型和 JVM 内存结构真