gpt4 book ai didi

asp.net - 使用variebyparam 和variebycustom 进行输出缓存

转载 作者:行者123 更新时间:2023-12-02 18:44:27 24 4
gpt4 key购买 nike

我正在尝试做一些应该非常简单的事情...我有一个带有下拉列表的网站,用户可以从中选择一个组。此后,用户使用菜单中的查询字符串参数在站点中导航。所以我希望缓存依赖于查询字符串 - 这似乎有效。我还希望缓存取决于他们选择的组。

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

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

我的varieByCustom代码如下所示:

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);

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

最佳答案

我最终确定了问题 - 当输出缓存放置在页面级别(而不是控制级别)时, session 不可用,并引发异常。由于此异常发生在全局错误处理程序之上的全局中,因此它会静默失败。我最终通过在 VaryByCustomString 和 Response.Write-ing 中的缓存键生成代码周围包装一个 try-catch block 来解决这个问题。

多么令人沮丧...无论如何,解决方案是在控制级别实现缓存,不幸的是,这需要更多工作,因为页面的各个部分协同工作...但这比没有缓存好。我希望这有助于节省其他人的时间。

底线:对于 global.asax 中的 VariableByCustomString - 在页面级别进行缓存时, session 不可用。

关于asp.net - 使用variebyparam 和variebycustom 进行输出缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6781155/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com