加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 输出缓存使用BOTH varybyparam和varybycustom

发布时间:2020-12-16 07:03:47 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试做一些非常简单的事情……我有一个带有下拉列表的站点,用户可以从中选择一个组.此后,用户使用菜单中的查询字符串参数浏览站点.所以我希望缓存依赖于查询字符串 – 这似乎有效.我还希望缓存依赖于他们选择的组. 但是当查询字符串为空时,缓存元素似
我正在尝试做一些非常简单的事情……我有一个带有下拉列表的站点,用户可以从中选择一个组.此后,用户使用菜单中的查询字符串参数浏览站点.所以我希望缓存依赖于查询字符串 – 这似乎有效.我还希望缓存依赖于他们选择的组.

但是当查询字符串为空时,缓存元素似乎都不起作用 – 该页面就是最后一个选定组的版本.我的缓存指令如下所示:

<%@ OutputCache Duration="300" VaryByCustom="currentAtomId" VaryByParam="documentId;folderId;sectionId;renderMode;typeId" %>

我的varyByCustom代码如下所示:

public override string GetVaryByCustomString(HttpContext context,string custom)
{
    switch (custom)
    {
        case "currentAtomId":
            var currentAtomId = SecurityManifold.Create().CurrentAtomId;

            var returnString = currentAtomId == null ? Guid.NewGuid().ToString() : currentAtomId.ToString();

            return returnString;

        default:
            throw new ArgumentException(string.Format("Argument '{0}' is not a valid cache argument.",custom));
    }
}

对CurrentAtomId的调用归结为:

public static int? GetCurrentAtomIdFromContext(HttpContext context)
{
    int entityId;

    if (context.Session == null)
    {
        throw new InvalidOperationException("Session is null");
    }

    var sessionEntityId = context.Session["CurrentEntityId"];

    if (sessionEntityId == null || string.IsNullOrEmpty(sessionEntityId.ToString()))
    {
        return null;
    }

    if (!int.TryParse(sessionEntityId.ToString(),out entityId))
    {
        return null;
    }

    return entityId;
}

最后,指定CurrentEntityId的代码是这样的:

var selectedEntityId = this.lstSecurityEntities.SelectedValue;

    if (string.IsNullOrEmpty(selectedEntityId))
    {
        return;
    }

    Session["CurrentEntityId"] = selectedEntityId;

    var possibleQueryString = Request.QueryString.ToString();

    if (!string.IsNullOrEmpty(possibleQueryString))
    {
        possibleQueryString = "?" + possibleQueryString;
    }

    Response.Redirect("default.aspx" + possibleQueryString);

我很困惑.任何想法将不胜感激.

解决方法

我最终确定了问题 – 当输出缓存放在PAGE级别(而不是控件级别)时,会话不可用,并抛出异常.因为全局错误处理程序Global ABOVE中发生此异常,所以它会以静默方式失败.我最终通过在VaryByCustomString中包含缓存密钥生成代码的try-catch块和Response.Write-out来解决这个问题.

无论如何,最重要的是,解决方案是在控制级别实现缓存,遗憾的是,由于页面的各个部分协同工作,所以工作量要大得多……但它比没有缓存更好.我希望这有助于拯救别人一些时间.

底线:对于global.asax中的varyByCustomString – 在页面级别高速缓存时无法使用会话.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读