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?
Output caching provides you with a very easy method of dramatically improving the performance of your ASP.NET MVC applications. In this tutorial, you learned how to use the [OutputCache] attribute to cache the output of controller actions.
ASP.NET versions 2.0 to 3.5 included ASP.NET Mobile Controls: a set of server controls for mobile devices in the System.Web.Mobile.dll assembly and the System.Web.UI.MobileControls namespace. The assembly is still included in ASP.NET 4, but it is deprecated.
The OutputCache attribute is used to cache the content returned by a controller action method, so that, the same content does not need to be generated each and every time the same controller action is invoked. OutputCache attribute has several properties. Why do we need Caching?
By default, when you use the [OutputCache] attribute, content is cached in three locations: the web server, any proxy servers, and the web browser. You can control exactly where content is cached by modifying the Location property of the [OutputCache] attribute. You can set the Location property to any one of the following values:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With