ASP.NET Core 1.0.1 Hosting: Session.Abandon() Method in ASP.NET

The HttpSessionState.Abandon() method destroys all objects stored in a Session object and releases their resources. We call this method in ASP.Net with Session.Abandon(). This method has no parameters and has no return value.

For using Abandon() method you must add System.Web.dll file to the project and also use System.Web.SessionState namespace in the header page. When this method is called, the current session is not deleted until all of the scripts on the current page have been processed. This means that it is possible to access session variables on some pages as the call to Abandon, but not from another web page.


For example in the following script, the Index() method prints the value C-SharpCorner. This is because the Session object is not destroyed until the server has finished processing the script.


Now if you access the variable MyName on a subsequent Web page, it is empty. This is because MyName is destroyed with the previous Session object when the page containing the previous example finished processing.

The server creates a new Session object when you open a subsequent Web page, after abandoning a session. You can store variables and objects in this new Session object.

If you want to use the Session.Abandon() in Index() method and also the last line in this method, you define a new session with some value that we want in the other page — select this session to get data value! Value is null because Abandon() method destroys all objects stored in a Session object and releases their resources. What’s the solution?

For solving this problem you define ActionHelper and pass the value that you want to save in the session and use in the other page, now the last process is finished and you can set the value in the new session as in the following sample,

Now you can access the mode variable in the session.