0

I decided to implement caching to improve the performance of the product pages.

Each page contains a large amount of the product's images.

I created the following code in a Razor view.

@{   
var productID = UrlData[0].AsInt();
var cacheItemKey = "products"; 
var cacheHit = true; 
var data = WebCache.Get(cacheItemKey);

var db = Database.Open("adldb");
if (data == null) { 
cacheHit = false; 
} 
if (cacheHit == false) {   
data = db.Query("SELECT * FROM Products WHERE ProductID = @0", productID).ToList();
WebCache.Set(cacheItemKey, data, 1, false);
}
}

I'm using the data with the following code:

@foreach (dynamic p in data)
{
<a href="~/Products/View/@p.ProductID"
<img src="~/Thumbnail/@p.ProductID"></a>
}

The caching code works well, but when passing the new query string parameter (changing the version of the page) the result in browser is the same for the declared cashing time.

How to make caching every version of the page?

Thanks

Oleg

1 Answers1

0

A very simple approach might be to convert your key (productID) to a string and append it to the name of your cacheItemKey.

So you might consider changing the line:

var cacheItemKey = "products"; 

to read:

var cacheItemKey = "products" + productID.ToString();

This should produce the behavior you are looking for -- basically mimicking a VaryByParam setup.

ps. Please keep in mind I have not added any sort of defensive code, which you should do.

Hope that helps.

David Tansey
  • 5,813
  • 4
  • 35
  • 51
  • Thanks David, that did it! But what does it mean "add any sort of defensive code"? I'm not familiar with this. – user879356 Mar 26 '13 at 15:05
  • I was thinking about maybe a test for `NULL` on `productID` before calling `ToString()` but I think if there was an issue with the data it will probably fail at the `AsInt()` in your sample code... By 'defensive code' I simply mean adding code to test assumptions, usually related to datatypes. Here's a link to Wikipedia's entry on Defensive Programming, which says far better than I can. http://en.wikipedia.org/wiki/Defensive_programming – David Tansey Mar 26 '13 at 18:28
  • I would be very grateful if you would mark my answer as the accepted answer. Have a great day. – David Tansey Mar 26 '13 at 18:30
  • Thanks a Lot David for your answer! It was really useful. Regards. Oleg – user879356 Apr 03 '13 at 12:53