ASP.Net MVC4移动感知输出缓存

Jam*_*ers 12 asp.net-mvc-4

我正在努力将应用程序从MVC3升级到MVC4,并注意到我认为(希望?)会"正常工作"的东西.

码:

[OutputCache(Duration = 600, VaryByParam = "none")]
public ActionResult Index()
{
   return View();
}
Run Code Online (Sandbox Code Playgroud)

这是ASP.Net的教科书缓存示例.每当浏览器点击页面时,它会检查缓存以查看是否存在某些内容,如果没有则生成视图,然后发送缓存的结果.

这很好用; 但是,在使用MVC4的Mobile视图功能时,我注意到上面的代码没有检查请求是否来自移动设备.因此,如果我在桌面上点击该路线,桌面视图将显示在我的手机上,直到缓存无效.反之亦然(如果我首先使用手机点击页面,则桌面将会看到移动视图).

是否有一个参数可以用来使我的工作像我希望的那样,或者我正在构建一个客户OutputCacheProvider?

Jam*_*ers 25

经过一番挖掘后,我找到了解决问题的方法.

更新控制器操作

[OutputCache(Duration = 600, VaryByCustom = "IsMobile")]
public ActionResult Index()
{
   return View();
}
Run Code Online (Sandbox Code Playgroud)

覆盖Global.asax中的GetVaryByCustomString

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if (custom.ToLowerInvariant() == "ismobile" && context.Request.Browser.IsMobileDevice)
    {
        return "mobile";
    }
    return base.GetVaryByCustomString(context, custom);
}
Run Code Online (Sandbox Code Playgroud)


小智 5

这是正确的GetVaryByCustomString方法

public override string GetVaryByCustomString(HttpContext context, string custom)
    {
        if (custom.ToLowerInvariant() == "ismobile")
        {
            return context.GetVaryByCustomStringForOverriddenBrowser();
        }
        return base.GetVaryByCustomString(context, custom);
    }
Run Code Online (Sandbox Code Playgroud)