Of Code and Me

Somewhere to write down all the stuff I'm going to forget and then need

Use CacheProfile attribute with output caching in asp.net mvc November 22, 2009

Filed under: Asp.Net,C#,MVC,Web — Rupert Bates @ 9:21 pm

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!

Advertisements
 

One Response to “Use CacheProfile attribute with output caching in asp.net mvc”

  1. […] to VoteUse CacheProfile attribute with output caching in asp.net mvc (11/22/2009)Sunday, November 22, 2009 from Rupert BatesI’ve recently been setting up some caching on a new […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s