c# - 启用 OutputCache 时 session 丢失

标签 c# asp.net-mvc session caching asp.net-mvc-5

我有一个(工作中的)MVC 应用程序,它在多个部分使用 Session 属性:

return httpContext.Session[SPContextKey] as SharePointAcsContext;

(忽略这是共享点;此问题不是特定于 SP 的)

在我尝试启用 Outputcaching 之前一切正常:

[OutputCache (Duration =600)]
public ActionResult Select() {
  DoSelect();
}

当内容被缓存时,httpContext.Session 变为 NULL。

有没有办法在保留 session 数据的同时使用缓存?

最佳答案

我自己找到了解决方案。我花了一段时间才得出结论 - 如果数据被缓存 - 根本不应该运行任何单独的代码。原因应该是缓存的主要目的:当数据被兑现时不要运行任何代码。

这使我得出结论,导致问题的代码必须在缓存之前运行。所以“坏男孩”很容易找到。另一个属性(在本例中为 AuthorizeAttribute)位于代码中的 OutputCache-Attribute 之前,当缓存应用但无法访问 Session 时,该属性仍在运行:

[Route("{id}")]
[UserAuth(Roles =Directory.GroupUser)]
[JsonException]
[OutputCache(Duration = 600)]
public ActionResult Select()
{
  DoSelect();
}

将 UserAuth-Attribute 放在 OutputCache-Attribute 下方解决了问题

关于c# - 启用 OutputCache 时 session 丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36161509/

相关文章:

session - 成功验证后 symfony2 安全 token /上下文丢失( session 正在运行)

c# - 比较 LINQ 方法语法中的 2 个数字列表

c# - 使用 C# 反射调用构造函数

c# - Selenium 单击下拉菜单中的标题

c# - 如何获取模型的 "description"属性而不是 "name"属性 - (MVC asp.net)

asp.net - Redis session 状态提供程序使 session 无效

C#。 OpenTK 与 OpenGL 的代码相同吗?

ASP.NET Core 错误 : The JSON value could not be converted to System. 字符串

c# - 如何使用 MVC 重定向到网站?

javascript - session Cookie 在 IE11 中有错误行为?