针对不同的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 @ 2014-10-26 14:00  Create Chen  阅读(2241)  评论(0编辑  收藏  举报