Workaround
Here is a relatively easy and transparent way to get around this bug:- Use VaryByCustom output cache parameter for the actions.
- Use the cache profile support to implicitly inject your VaryByCustom parameter to your output cache.
- Implement the custom parameter handling in your Global.asax.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[OutputCache(CacheProfile = "Short", VaryByParam = "containerName", VaryByCustom="MobileVsDesktopCache")] | |
public ActionResult MyAction(string containerName) | |
{ | |
//... | |
} |
This is repetitive, so we want to avoid sprinkling this custom attribute everywhere. We can use the cache profile support in your
Web.config
to add this attribute implicitly. (Just set the timeouts in your config).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<system.web> | |
<caching> | |
<outputCacheSettings> | |
<outputCacheProfiles> | |
<add name="Long" duration="0" varyByCustom="MobileVsDesktopCache" /> | |
<add name="Medium" duration="0" varyByCustom="MobileVsDesktopCache" /> | |
<add name="Short" duration="0" varyByCustom="MobileVsDesktopCache" /> | |
</outputCacheProfiles> | |
</outputCacheSettings> | |
</caching> | |
</system.web> |
So, now your
OutputCache
annotation becomes:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[OutputCache(CacheProfile = "Short", VaryByParam = "containerName")] |
Finally, we implement the custom cache handling in the
Global.asax.cs
:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public override string GetVaryByCustomString(System.Web.HttpContext context, string custom) | |
{ | |
if (custom == "MobileVsDesktopCache") | |
{ | |
return Request.Browser.IsMobileDevice ? "Mobile" : "Desktop"; | |
} | |
return base.GetVaryByCustomString(context, custom); | |
} |
No comments:
Post a Comment