Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

asp.net - programmatically control output caching - disable or enable cache according to parameter value

We've got a fairly standard e-commerce scenario with paged lists of products within categories. For better or worse, about 80% of visitors never navigate past the first page, depending on the category there may then be 5-10 more pages of results which are viewed far less often. (Yes we do optimise what appears on the first page and have good search - but that's a different discussion)

We can't cache every single page of results, because we're constrained by memory, but the benefit of caching just the first page of results for each category would be huge.

I know I could do something similar using object caching to store the datasets in question, but is this possible using output caching, perhaps by using the response.Cache object?

Where in the page lifecycle could this be done? Pre-render?

Much simplified, the URL is something like "/ProductList?Category=something&Page=1" And I'd want logic something like (pseudocode):

If paramater "Page" equals 1
   Use output caching: vary by param = "categoryName; page"
else
   Don't use caching at all, just render the page from scratch.

We're using ASP.NET 2.0, on IIS 6/win2003.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of using the OutputCache directive, you can do the same thing programmatically, as follows:

if (yourArbitraryCondition) {
  OutputCacheParameters outputCacheSettings = new OutputCacheParameters();
  outputCacheSettings.Duration = 60;
  InitOutputCache(outputCacheSettings);
}

Doing this from OnInit should work fine. And obviously, you can tweak the caching behavior by setting the various properties on the OutputCacheParameter, which has all the same knobs as the directive (in fact, that's what we generate when you use the directive).

The key point is that you're only executing this logic conditionally, while the directive makes it unconditional.

UPDATE:

As an alternative, you can use the low level cache API that the code above is built on. e.g.

HttpCachePolicy cache = Response.Cache;
cache.SetCacheability(HttpCacheability.Public);
cache.SetExpires(Context.Timestamp.AddSeconds(60));
cache.VaryByParams["categoryName"] = true;

Basically, it's another way of doing the same thing, without using any API's marked as 'should not be called'. In the end, either way will work, so take your pick.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...