I’ve recently been setting up some caching on a new Asp.Net MVC site by using the OutputCache attribute on my controllers:
//cache this for an hour
[OutputCache(Duration=60 * 60, VaryByParam="")]
This works really well except that it means hard codeding the cache time into my app so if I want to change it I need to recompile and deploy my code which is obviously far from ideal. So I changed my code to load the value from the web.config and ran into this error:
‘An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type’
Not very helpful.
But fortunately there is a better way of doing all this using cache profiles, I just set up a cache profile in my web.config:
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="HomePage" duration="3600" varyByParam="None" location="ServerAndClient"/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>
</system.web>
And then reference this in my attribute:
[OutputCache( CacheProfile="HomePage")]
And bingo, we’re sucking diesel as a friend of mine says!