针对不同的Cookie做页面缓存
有时我们需要为PC浏览器及移动浏览器生成不同的页面,为了提高性能,不能每次请求都去判断User-Agent,通常用一个 Cookie 标记一下客户端是否是移动客户端,这样只需要读取这个 Cookie 的值就知道这个请求是否是移动端。
这里主要通过 OutputCacheByCustom 来实现对不同的 Cookie 值生成不同的页面,具体做法也比较简单:
1. 在 Global.asmx.cs 里重写 GetVaryByCustomString 函数
这个函数接受两个参数,第一个是 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()); } }
以上两步就可以了,当然也可以将缓存方案写进 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 相应的位置只需指定 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
作者:Create Chen
出处:http://technology.cnblogs.com
说明:文章为作者平时里的思考和练习,可能有不当之处,请博客园的园友们多提宝贵意见。
本作品采用知识共享署名-非商业性使用-相同方式共享 2.5 中国大陆许可协议进行许可。
标签:
asp.net mvc
, 页面缓存
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库