有时咱们须要为PC浏览器及移动浏览器生成不一样的页面,为了提升性能,不能每次请求都去判断User-Agent,一般用一个 Cookie 标记一下客户端是不是移动客户端,这样只须要读取这个 Cookie 的值就知道这个请求是不是移动端。web
这里主要经过 OutputCacheByCustom 来实现对不一样的 Cookie 值生成不一样的页面,具体作法也比较简单:浏览器
这个函数接受两个参数,第一个是 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); } }
public class CacheController : Controller { [OutputCache(Duration=60, VaryByCustom="IsMobile",Location=OutputCacheLocation.Server)] public ActionResult Index() { return Content(DateTime.Now.ToString()); } }
以上两步就能够了,固然也能够将缓存方案写进 Web.config 配置文件中:cookie
<system.web> <caching> <outputCacheSettings> <outputCacheProfiles> <clear /> <!-- 60 seconds--> <add varyByCustom="IsMobile" duration="60" name="ChangeByDevice" location="Server" /> </outputCacheProfiles> </outputCacheSettings> </caching> </system.web>
在 View 相应的位置只需指定 OutputCache 的 CacheProfileide
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/indexspa
Output:2014/10/26 13:58:16code