Jay Tuley

Posts tagged with outputcache

Cache Details are Important. by Jay

So again I’m trying to get back in the habit of blogging. I typically stick to blogging about Mac programming, however I do so much more .NET programming these days, and I come across a lot of interesting issues when .NET programming that I’m not going to stick to strictly Mac topics anymore.

So at work our website is a mini content management system, built with ASP.NET MVC and SQLite. From this CMS system we have built in support to link to other web applications. I had been doing this with just a plain redirect if a content page is marked as a link content page. However, these web apps were running on our own server, now we have a very minor app from a vendor that is hosted on their server. They provide sufficient branding customization except for the url of course. So I added url masking as a new option to our CMS system. MVC made this easy, I just added another database field, a new view template that provided the frameset for the url mask and a quick check in the view action.

That part went fine, however I needed to add another feature, this url I was masking used SSL, so I needed the frameset to be sent over SSL too so the user would get a lock. Not a big issue, I just needed to make sure if the user typed in the address and it defaulted to http that it would automatically redirect to https. So I add a check in the view action to check if the requested scheme was not https and content required https and then redirected to https. And this would redirect to the https masked url the first time but the second time it would stay http, it was totally weird. A little debugging discovered that the action wasn’t being called the second time. OutputCache!! Since it’s a CMS I use to OutputCache to get serious performance benefit without worry (typically) of outdated content since the CMS is interactively updated it’s cache is interactively invalidated.

So where did I go wrong here. Well my mental model of OutputCache missed 2 details, first that redirects aren’t cached by the OutputCache, and second that OutputCache does not vary by the full url (sans query string). Once I figured what was going on my ultimate solution was quite easy I just need to ensure that the cache varied by url protocol as well. I first looked for a http request header that might differ between a http and https request, however I couldn’t find one and it didn’t seem reasonable that one would exist, so I used Microsoft’s convenient varyByCustom attribute for the OutputCache.

public override string GetVaryByCustomString(HttpContext context, string custom){
	if(custom == "scheme"){
		return context.Request.Url.Scheme;
	}return null;
}

One simple if statement and my cache varies by protocol and then my code worked as it should, and now I have a better mental model of the ASP.NET OutputCache.