读取用户会话时HttpRuntime CacheInternal NULL引用异常(反射)

时间:2017-07-11 16:57:38

标签: c# asp.net reflection iis-7 reflectionpermission

在我们的Windows服务器上进行一些更新后(2008R2,2012)Asp.net应用程序抛出错误:

var obj_1 = typeof(HttpRuntime).GetProperty("CacheInternal", BindingFlags.NonPublic | BindingFlags.Static); 

CacheInternal会变为null,不知道为什么?

以下解决方案无效:( Solution

enter image description here

3 个答案:

答案 0 :(得分:3)

我找到了解决方案。现在HTTPRuntime类没有CacheInternal属性。为了实现上述任务,我创建了一个全局列表,在Session_Start中的该列表中添加会话,并删除Global.asax的Sessions_end函数中的会话。

答案 1 :(得分:2)

该内部成员存在于.NET 2.0中,并在.NET 3.5和.NET 4.6.1之间消失。这就是为什么你不应该使用反思来依赖非公共成员。它们可以随时消失或重命名。

由于.NET是向后兼容的,因此强制某个运行时版本不会在运行时使用较旧的程序集,如果有更新的程序集可用:.NET 4.6.1仍然是所有早期版本的就地升级到4.0。< / p>

所以我认为这个更新要么修改成员远离System.Web程序集,要么从未在4.0开始,并且您的应用程序池以某种方式从.NET 2.0更改为.NET 4.0。

当然不建议卸载更新,但您可以尝试找到删除此成员的那个。然后,您必须验证它不是安全更新。

或者强制应用程序在.NET 2.0下运行,如果可行的话。

您还可以尝试找到解决原始问题的不同方法。

答案 2 :(得分:2)

我找到了一个可能现在最好的解决方案。如果有人有另一个,请告诉我!

  object aspNetCacheInternal = null;

  var cacheInternalPropInfo = typeof(HttpRuntime).GetProperty("CacheInternal", BindingFlags.NonPublic | BindingFlags.Static);
  if (cacheInternalPropInfo == null)
  {
    // At some point, after some .NET Framework's security update, that internal member disappeared.
    // https://stackoverflow.com/a/45045160
    // 
    // We need to look for internal cache otherwise.
    //
    var cacheInternalFieldInfo = HttpRuntime.Cache.GetType().GetField("_internalCache", BindingFlags.NonPublic | BindingFlags.Static);

    if (cacheInternalFieldInfo != null)
    {
      var httpRuntimeInternalCache = cacheInternalFieldInfo.GetValue(HttpRuntime.Cache);
      var httpRuntimeInternalCacheField = httpRuntimeInternalCache.GetType().GetField("_cacheInternal", BindingFlags.NonPublic | BindingFlags.Instance);

      if (httpRuntimeInternalCacheField != null)
        aspNetCacheInternal = httpRuntimeInternalCacheField.GetValue(httpRuntimeInternalCache);
    }
  }
  else
  {
    aspNetCacheInternal = cacheInternalPropInfo.GetValue(null, null);
  }

  return aspNetCacheInternal;

问候!