WebTrainingRoom Online Courses
Online Training for Asp.net MVC Web Designing Development, MS SQL, Digital Marketing

How to use Session in Asp.net MVC

Session in Asp.net MVC

In this article, we will learn three different ways to work with session management in ASP.NET MVC

What is session in Asp.net MVC
The Web is stateless, In simple word Session is a temporary memory location where we can hold small amount of data for a certain period of time during user visit on any website, Session is a HttpSessionStateBase object.

Asp.net provide three different way to store session data. InProc, StateServer and SQLServer

Let's look at some example of how we can store data in session object, here at login controller we are storing a user object, which has some user specific data fetched from database.

So after every user logs in we pull username, age, address in "UserObject" from database, now user keep on moving from one page to another page, We can display customized message on every page.

public ActionResult login(LoginModel model)
    // this is a custome object holding user data
    Session["userInfo"] = UserObject; 

    return View();

Now assume user on mydashboard page, where we want to show a welcome message to user, now we can get the information from session object, we don't need to make any database call.

public ActionResult mydashboard()             
    UserObject _uobj=Session["userInfo"] as  UserObject;

    return View();

We also can use the session object for security purpose, suppose on mydashboard page we want to display user account balance, and if userobject is null or invalid, we simply can redirect user to login page and ask to log in again

You can access session object in your razor view directly this way
UserObject _uobj = Session["userInfo"] as UserObject;
if (_uobj!=null)
<div>Hello @_uobj.UserFullName</div>

sessionState mode is specified in web.config, default mode is "InProc", you can also change the time duration.

<sessionState mode="InProc" timeout="5" />

Name Email Website
Session Management in Asp.net MVC