C# OutputCache with subdomains C# OutputCache with subdomains

The other day I was working on a project that was leveraging OutputCache. This little attribute is a fantastic way to implement caching in an MVC project. This was working great until I encountered a snag when using a subdomain.


Configuration CacheProfile

It was being used as follows but it was not working when we had multiple subdomains sharing the same controllers and actions:


[OutputCache(CacheProfile="CacheProfile")]
public ActionResult Index()
{
return View();
}

To make things more consistent across all methods that require caching, we defined a CacheProfile. This CacheProfile can then be setup in the Web.config as follows:


<caching>
<outputCacheSettings>
<outputCacheProfiles>
<!-- https://msdn.microsoft.com/en-us/library/ms164606(v=vs.100).aspx -->
<add name="CacheProfile" duration="31557600" enabled="true" varyByParam="*" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>

By default we are caching for one year. We also want our caching to not simply cache the index page for all requests. Instead we included a varyByParam option that will tell the caching mechanism to cache different pages by the parameters passed into that page.

For us this started working great. However, things randomly started going a miss. Our project was sharing the same controllers and views for multiple subdomains. Each subdomain had it's on styling, but the controllers and views contained the same content.

varyByHeader to the rescue

After much headache and research, we discovered that when you share code between different subdomains or even different domains, it's important to include this configuration option: varyByHeader="Host"

This configuration option goes in the Web.config in the CacheProfile key next to the varyByParam.

Thanks to Zygimantas from When using OutputCache with MVC, sub.domain.com gives me www.domain.com cached page.

This saved the entire team over a day of research and head banging! Upvote the answer as it is well deserved!

Published on May 4, 2018

Tags: Optimization | ASP.NET MVC and Web API Tutorial

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.