12

I'm working on upgrading an application from MVC3 to MVC4 and noticed something that I assumed (hoped?) would "just work".

CODE:

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

This is a textbook caching example for ASP.Net. Whenever a browser hits the page, it checks the cache to see if something exists, generates the view if not, and then sends the cached results.

This works great; however, playing around with the Mobile view functionality of MVC4, I noticed that the above code does not check to see if the Request is from a Mobile Device. So if I hit that route on a desktop, the desktop view will be displayed on my phone until cache is invalidated. The reverse is true as well (if I first hit the page with a phone, the desktop will then see the mobile view instead).

Is there a parameter that I could use to make this work like I hoped or am I looking at building a customer OutputCacheProvider?

2 Answers 2

25

After a bit more digging, I found a solution to the issue.

Updated Controller Action

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

Override GetVaryByCustomString in Global.asax

public override string GetVaryByCustomString(HttpContext context, string custom)
{
    if (custom.ToLowerInvariant() == "ismobile" && context.Request.Browser.IsMobileDevice)
    {
        return "mobile";
    }
    return base.GetVaryByCustomString(context, custom);
}
4
  • 1
    Switching to desktop view doesn't work with this code. The page simply refreshes instead of switching. Use context.GetVaryByCustomStringForOverriddenBrowser() instead. Oct 21, 2013 at 23:29
  • @PavelChuchuva some time this code not switching to Desktop , Why ?
    – Moslem7026
    Jan 25, 2020 at 6:13
  • @Moslem7026 No idea, sorry. Would you please try to reliably reproduce this problem and then ask another question? Jan 27, 2020 at 9:47
  • @PavelChuchuva unfortunately i cant reproduce , but some time it occurs , load mobile cached version for all mobile and desktop requests
    – Moslem7026
    Jan 28, 2020 at 14:41
5

This is Correct GetVaryByCustomString method

public override string GetVaryByCustomString(HttpContext context, string custom)
    {
        if (custom.ToLowerInvariant() == "ismobile")
        {
            return context.GetVaryByCustomStringForOverriddenBrowser();
        }
        return base.GetVaryByCustomString(context, custom);
    }
1
  • some times it locks on mobile and not swiched to desktop
    – Moslem7026
    Jan 25, 2020 at 6:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.