JamesEggers
JamesEggers

Reputation: 12936

ASP.Net MVC4 Mobile-Aware OutputCache

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?

Upvotes: 12

Views: 2395

Answers (2)

Thanh Tung
Thanh Tung

Reputation: 105

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);
    }

Upvotes: 5

JamesEggers
JamesEggers

Reputation: 12936

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);
}

Upvotes: 25

Related Questions