在启用OutputCache时,会话将丢失。

时间:2022-01-23 06:35:30

I have a (working) MVC-application that uses Session properties on multiple parts:

我有一个(正在工作的)mvc应用程序,它在多个部分上使用会话属性:

return httpContext.Session[SPContextKey] as SharePointAcsContext;

(ignore that this is sharepoint; This problem isn't be SP-specific)

(忽略这是sharepoint;这个问题不是特定于sp的)

This works fine until I try to enable Outputcaching:

在我尝试启用outputcache之前,这是可行的:

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

When the content is cached, httpContext.Session becomes NULL.

当缓存内容时,使用httpContext。会话变成零。

Is there a way to keep the Session data and also use caching?

是否有方法保存会话数据并使用缓存?

1 个解决方案

#1


1  

I found the solution myself. It took a while until I came to the conclusion that - if the data is cached - there shouldn't be any individual code at all that is run. Cause that should be the main purpose of the cache: Don't run any code when the data is cashed.

我自己找到了解决办法。我花了一段时间才得出这样的结论:如果数据被缓存,那么就不应该运行任何单独的代码。因为这应该是缓存的主要目的:当数据被压缩时,不要运行任何代码。

That led me to the conclusion that the code causing the problem must be run before the cache. And so the "bad boy" was easy to find. Another attribute (in this case an AuthorizeAttribute) that is before the OutputCache-Attribute in the code is still run when caching applies but cannot access the Session:

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

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

Putting the UserAuth-Attribute BELOW the OutputCache-Attribute solved the problem

将UserAuth-Attribute放在OutputCache-Attribute下面解决了这个问题

#1


1  

I found the solution myself. It took a while until I came to the conclusion that - if the data is cached - there shouldn't be any individual code at all that is run. Cause that should be the main purpose of the cache: Don't run any code when the data is cashed.

我自己找到了解决办法。我花了一段时间才得出这样的结论:如果数据被缓存,那么就不应该运行任何单独的代码。因为这应该是缓存的主要目的:当数据被压缩时,不要运行任何代码。

That led me to the conclusion that the code causing the problem must be run before the cache. And so the "bad boy" was easy to find. Another attribute (in this case an AuthorizeAttribute) that is before the OutputCache-Attribute in the code is still run when caching applies but cannot access the Session:

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

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

Putting the UserAuth-Attribute BELOW the OutputCache-Attribute solved the problem

将UserAuth-Attribute放在OutputCache-Attribute下面解决了这个问题