以编程方式控制输出缓存 - 根据参数值禁用或启用缓存

And*_*w M 20 asp.net iis-6 outputcache

我们有一个相当标准的电子商务场景,其中包含类别中的产品分页列表.无论好坏,大约80%的访问者从未浏览过第一页,根据类别,可能会有5-10多个结果页面,这些页面的查看次数要少得多.(是的,我们会优化第一页上显示的内容并进行良好的搜索 - 但这是一个不同的讨论)

我们无法缓存每一页的结果,因为我们受到内存的限制,但是缓存每个类别的第一页结果的好处将是巨大的.

我知道我可以使用对象缓存来存储有问题的数据集,但这可能是使用输出缓存,也许是通过使用response.Cache对象?

页面生命周期中的哪个位置可以完成?预渲染?

很简单,URL就像"/ ProductList?Category = something&Page = 1"而且我想要逻辑类似(伪代码):

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.
Run Code Online (Sandbox Code Playgroud)

我们在IIS 6/win2003上使用ASP.NET 2.0.

Dav*_*bbo 31

您可以通过编程方式执行相同的操作,而不是使用OutputCache指令,如下所示:

if (yourArbitraryCondition) {
  OutputCacheParameters outputCacheSettings = new OutputCacheParameters();
  outputCacheSettings.Duration = 60;
  InitOutputCache(outputCacheSettings);
}
Run Code Online (Sandbox Code Playgroud)

从OnInit执行此操作应该可以正常工作.显然,您可以通过在OutputCacheParameter上设置各种属性来调整缓存行为,OutputCacheParameter具有与指令相同的旋钮(事实上,这是我们在使用指令时生成的).

关键是你只是有条件地执行这个逻辑,而指令使它无条件.

更新:

作为替代方案,您可以使用上面代码构建的低级缓存API.例如

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

基本上,这是做同样事情的另一种方式,不使用任何标记为"不应该被调用"的API.最后,无论哪种方式都有效,请选择.


Jos*_*ger 5

编辑: 我比David Ebbo的回答要好得多.


你可以用

<%@ OutputCache Duration="60"  VaryByParam="none" VaryByCustom="pageOne" %>
Run Code Online (Sandbox Code Playgroud)

并以一种方式实现它,返回第一页的固定键和所有其他页的随机键.您可以(并且应该)让清理机制处理内存,但HttpResponse.RemoveOutputCacheItem如果必须,可以使用删除缓存项.

public override string GetVaryByCustomString(HttpContext ctx, string custom)
{
    if(custom == "pageOne")
    {
        if(ctx.Request["page"] == "1")
        {
            return "1";
        }

        HttpResponse.RemoveOutputCacheItem("/Default.aspx");
        return Guid.NewGuid().ToString();
    }
    return base.GetVaryByCustomString(ctx, custom);
}
Run Code Online (Sandbox Code Playgroud)