ASP.NET MVC > Session management

Store user specific data into session in ASP.NET MVC

How to store user specific data into session?


To store data in session, we do as we used to do in ASP.NET Web Form.

Session stores the data in key and value format. Value gets stored in object format, so any type of data (string, integer, class collection etc.) can be stored into the Session.

CODE IN CONTROLLER ACTION METHOD

To store data into Session, we can use below approach.

Session["MySession"] = DateTime.Now; // specific to user

Here key is “MySession” and data is today’s date.

To set the data only if there is no existing data in the session

if (Session["MySession"] == null)
      {
          Session["MySession"] = DateTime.Now; // specific to user
      }

Removing a specific data from session

      Session.Remove("MySession"); // remove this session value only specific to this suer

Removing all data from session.

Session.RemoveAll(); // removes all session value specific to this user
Session.Clear();
 Views: 38064 | Post Order: 94



Write for us






Hosting Recommendations