Use System.Web.HttpContext.Current.Session in custom class library CS file to get session prompt Error: Object reference not set to an instance of an object.
In general, it is not a problem to get the session value in this way, but pay special attention to the use of the session must be Page_Load method execution to establish the Page object after the session is used to target, It is not an error to detect if the session is null before calling the value.
If you define a global variable directly in page pages, the value of session will prompt you not to set an instance error! You should also pay attention to this problem with Application,cookie.
In the ASHX general handler file to invoke the session must inherit the System.Web.SessionState.IRequiresSessionState interface, in order to achieve session read and write!
The interface of System.Web.SessionState is introduced:
- ireadonlysessionstate Specifies that the destination HTTP handler requires only read access to the session-state value. This is a markup interface and there is no method.
- IRequiresSessionState Specifies that the destination HTTP handler requires read and write access to the session-state value. This is a markup interface and there is no method.
Custom HTTP handlers, inherited from IHttpHandler, have no problem writing system.web.httpcontext.current.session["Name", but when you want to write this Session to a variable, The workaround for finding the session value is NULL;MSDN: "Implement the IRequiresSessionState interface in a custom HTTP handler to determine if the handler needs read-write access to the session-state value", and after adding the interface to the custom class, Session value gets normal.
System.Web.HttpContext.Current.Session Get value Error