针对不同的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

posted @   Create Chen  阅读(2255)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示