ChatGPT解决这个技术问题 Extra ChatGPT

What should I do if the current ASP.NET session is null?

In my web application, I do something like this to read the session variables:

if (HttpContext.Current.Session != null &&  HttpContext.Current.Session["MyVariable"] != null)
{
    string myVariable= (string)HttpContext.Current.Session["MyVariable"];
}

I understand why it's important to check why HttpContext.Current.Session["MyVariable"] is null (the variable might not have been stored in the Session yet or the Session has been reset for various reasons), but why do I need to check if HttpContext.Current.Session is null?

My understanding is that the session is created automatically by ASP.NET therefore HttpContext.Current.Session should never be null. Is this assumption correct? If it can be null, does it mean I should also check it before storing something in it:

if (HttpContext.Current.Session != null)
{
    HttpContext.Current.Session["MyVariable"]="Test";
}
else
{
    // What should be done in this case (if session is null)?
    // Is it possible to force the session to be created if it doesn't exist?
}
ASP.NET WebApi will have diferent behaviour, you can check it on Accessing Session Using ASP.NET Web API

C
Community

Yes, the Session object might be null, but only in certain circumstances, which you will only rarely run into:

If you have disabled the SessionState http module, disabling sessions altogether

If your code runs before the HttpApplication.AcquireRequestState event.

Your code runs in an IHttpHandler, that does not specify either the IRequiresSessionState or IReadOnlySessionState interface.

If you only have code in pages, you won't run into this. Most of my ASP .NET code uses Session without checking for null repeatedly. It is, however, something to think about if you are developing an IHttpModule or otherwise is down in the grittier details of ASP .NET.

Edit

In answer to the comment: Whether or not session state is available depends on whether the AcquireRequestState event has run for the request. This is where the session state module does it's work by reading the session cookie and finding the appropiate set of session variables for you.

AcquireRequestState runs before control is handed to your Page. So if you are calling other functionality, including static classes, from your page, you should be fine.

If you have some classes doing initialization logic during startup, for example on the Application_Start event or by using a static constructor, Session state might not be available. It all boils down to whether there is a current request and AcquireRequestState has been run.

Also, should the client have disabled cookies, the Session object will still be available - but on the next request, the user will return with a new empty Session. This is because the client is given a Session statebag if he does not have one already. If the client does not transport the session cookie, we have no way of identifying the client as the same, so he will be handed a new session again and again.


Just a quick update I found today. Session is not available on the page constructor! Only on the Init event or after that.
I just encountered an HttpContext.Current.Session == null is code called by a Page_Load event of a master page. Apparently, this can occur in the context of a page. If I inspect the HttpContext.Current object, most of it members are initialized, but CurrentNotification and IsPostNotification throw an error: {System.PlatformNotSupportedException}. Whatever the cause, this issue has not occurred in production, where it has run for years. The platform is Windows Server 2003 R2 SP2, the application has target framework .Net 3.5 and runs in IIS with session state enabled.
I have also found that, when IIS is serving a direct request for a resource file which exists on disk, such as a style sheet, HttpContext.Current.Session can be null to code in `Application_AcquireRequestState'. The request for the page itself, however, does make the session object available to code there. This is under MVC.NET 4 at least.
I think it could also be null if you are inside an output-cached MVC action.
E
Ed Bishop

The following statement is not entirely accurate:

"So if you are calling other functionality, including static classes, from your page, you should be fine"

I am calling a static method that references the session through HttpContext.Current.Session and it is null. However, I am calling the method via a webservice method through ajax using jQuery.

As I found out here you can fix the problem with a simple attribute on the method, or use the web service session object:

There’s a trick though, in order to access the session state within a web method, you must enable the session state management like so: [WebMethod(EnableSession = true)] By specifying the EnableSession value, you will now have a managed session to play with. If you don’t specify this value, you will get a null Session object, and more than likely run into null reference exceptions whilst trying to access the session object.

Thanks to Matthew Cosier for the solution.

Just thought I'd add my two cents.

Ed


thanks Ed, Session was appearing as null in the webmethod - adding this fixed it. +1
Well, when you are calling into a webservice, you use another request than for the page, so that statement is still correct, IMO.
MSDN docs here - the default value is false. Works like a charm.
m
mathijsuitmegen

If your Session instance is null and your in an 'ashx' file, just implement the 'IRequiresSessionState' interface.

This interface doesn't have any members so you just need to add the interface name after the class declaration (C#):

public class MyAshxClass : IHttpHandler, IRequiresSessionState

Thank you very much, session was null in my login class. When i added this code to my ashx handler it turned session on my class too
I think this answers the question quite well. Thanks so much.
e
erikvimz

In my case ASP.NET State Service was stopped. Changing the Startup type to Automatic and starting the service manually for the first time solved the issue.


K
KV Prajapati

ASP.NET Technical Articles

SUMMARY: In ASP.NET, every Web page derives from the System.Web.UI.Page class. The Page class aggregates an instance of the HttpSession object for session data. The Page class exposes different events and methods for customization. In particular, the OnInit method is used to set the initialize state of the Page object. If the request does not have the Session cookie, a new Session cookie will be issued to the requester.

EDIT:

Session: A Concept for Beginners

SUMMARY: Session is created when user sends a first request to the server for any page in the web application, the application creates the Session and sends the Session ID back to the user with the response and is stored in the client machine as a small cookie. So ideally the "machine that has disabled the cookies, session information will not be stored".


关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now