asp.net - ASP.NET MVC 3 中每用户缓存的 "Safe handle has been closed"

标签 asp.net asp.net-mvc-3 caching

我正在开发一个 Intranet,在其中使用 System.Web.Caching.Cache 缓存实现来存储数据。 我似乎无法解决“安全句柄已关闭”错误,该错误是由以下堆栈跟踪产生的:

[ObjectDisposedException: Safe handle has been closed]
 System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success) +0
 Microsoft.Win32.Win32Native.GetTokenInformation(SafeTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, UInt32& ReturnLength) +0
System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeTokenHandle tokenHandle, TokenInformationClass tokenInformationClass) +203
System.Security.Principal.WindowsIdentity.get_User() +94
System.Security.Principal.WindowsIdentity.GetName() +127
System.Security.Principal.WindowsIdentity.get_Name() +42

错误是在以下行生成的:

@if(intranet.Models.NyhederModels.isAdministrator(CachedVariables.getWP(User)))

其中getWP如下:

public static WindowsPrincipalEx getWP(System.Security.Principal.IPrincipal User)
{
    Cache context = HttpRuntime.Cache;
    WindowsPrincipalEx wp = context["windowsPrincipal_" + User.Identity.Name] as WindowsPrincipalEx;
    if (wp == null)
    {
         wp = new intranet.Models.WindowsPrincipalEx(User.Identity);
        context.Insert("windowsPrincipal_" + User.Identity.Name, wp, null, DateTime.Now.AddSeconds(15.0), Cache.NoSlidingExpiration);
    }
    return wp;
}

如您所见,缓存的 key 采用 UserPrincipal,以确保缓存的数据是基于每个用户的。我尝试使用 HttpContext.Current,其中缓存部分起作用,但由于这种情况是在每个请求的基础上发生的,因此每个页面仍会检索一次数据。

上面的代码在本地主机上完美运行,但在生产环境中运行时显示“安全句柄已关闭”。

被缓存的数据是对 Windows Active Directory 的查询结果(如果这有什么区别),并且 User 是 System.Security.Principal.IPrincipal 的实例。

对于这个在引入缓存后才出现的错误有什么想法吗?

提前谢谢

最佳答案

这是一个有点老的问题,但我今天在谷歌上搜索“安全句柄已关闭原理缓存”时遇到了这个问题。

当我将 WindowsPrincipal 对象添加到 HttpContext.Cache 以便我可以重用它进行模拟时,我遇到了同样的错误。我开始收到此错误。为了阻止此错误发生,我所做的就是不存储 WindowsPrincipal 对象,而是仅存储 WindowsIdentity.Token,然后使用新的 WindowsIdentity 创建一个新的 WindowsPrincipal,并传入缓存的 WindowsIdentity.Token。

关于asp.net - ASP.NET MVC 3 中每用户缓存的 "Safe handle has been closed",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7386938/

相关文章:

asp.net-mvc-3 - 模型绑定(bind)逗号分隔的查询字符串参数

c# - 您使用哪个 .NET Memcached 客户端,EnyimMemcached 与 BeITMemcached?

java - 重用缓存的实例

cocoa - 使用不符合 `NSCache` 的 `NSDiscardableContent` 对象?

ASP.Net 在 UIWebView 和 ASIHttpRequest 之间形成身份验证 cookie

asp.net-mvc - 将星号附加到标签

c# - 数据尚未插入数据库(使用 SqlDataSource)

jquery - asp.net mvc 3 使用 jquery 或 ajax 调用 Controller 的操作

asp.net - 获取 SignalR 中心内的完整 URL

c# - 控制 ASP.NET 主题 css 链接顺序放置