在SharePoint Web应用中访问Session对象时发生System.NullReferenceException异常

我们有个客户在SharePoint Web应用中集成自定义的代码到时,经常遇到System.NullReferenceException异常。通常来说,如果程序配置成了Web Garden或者非Session Affinity的负载均衡,现象容易出现。

但这次情况有所不同。

通过.NET异常捕获,发现它是在访问Session对象的时候发生的。

000007ff`00fc2067 e8d4bb58ec call system_web_ni+0x25dc40 (000007fe`ed54dc40) (System.Web.HttpContext.get_Current(), mdToken: 060003c6)

000007ff`00fc206c 803800 cmp byte ptr [rax],0

000007ff`00fc206f 488bc8 mov rcx,rax

000007ff`00fc2072 e8511453ec call system_web_ni+0x2034c8 (000007fe`ed4f34c8) (System.Web.HttpContext.get_Session(), mdToken: 060003e2)

000007ff`00fc2077 48bb98c6a37f01000000 mov rbx,17FA3C698h

000007ff`00fc2081 488b13 mov rdx,qword ptr [rbx]

>>> 000007ff`00fc2084 803800 cmp byte ptr [rax],0

代码片段如下:

HttpContext.Current.Session["userdata"] = "123";

为了解决这类问题,我们在Web.Config中显式地将EnableSessionState设为True。

<%@ Page EnableSessionState="True" %>

并确保所有相关的单独页面不在页面的级别设置这个值为False。之后,问题依然发生,在memory dump中,System.Web.SessionState.InProcSessionState对象不再出现。

再一次检查了SharePoint的Web.Config文件,发现ASP.NET的session模块被注释掉了:

<!-- <add name="Session" type="System.Web.SessionState.SessionStateModule"/> -->

 

结论

==========

对于当前的SharePoint Web应用,Session对象是默认不可访问的,因为SharePoint应用会移除Session模块,并设置EnableSessionState为False。当把Session模块加回去,并在Web.Config中设置EnableSessionState为True后,抛System.NullReferenceException异常的问题就解决了。

Freist from APGC DSI Team