日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

针对不同的Cookie做页面缓存

發(fā)布時間:2025/4/16 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 针对不同的Cookie做页面缓存 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

有時我們需要為PC瀏覽器及移動瀏覽器生成不同的頁面,為了提高性能,不能每次請求都去判斷User-Agent,通常用一個 Cookie 標(biāo)記一下客戶端是否是移動客戶端,這樣只需要讀取這個 Cookie 的值就知道這個請求是否是移動端。

這里主要通過 OutputCacheByCustom 來實現(xiàn)對不同的 Cookie 值生成不同的頁面,具體做法也比較簡單:

1. 在 Global.asmx.cs 里重寫 GetVaryByCustomString 函數(shù)

這個函數(shù)接受兩個參數(shù),第一個是 System.Web.HttpContext 對象,包含了對話的上下文,第二個是 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)然也可以將緩存方案寫進 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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。