Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session Management in MVC

I am new in MVC. I am creating new WebApplication in MVC4 Razor. I want to maintain User Login session for all pages. Can any one Explain me how to maintain session for all views in MVC with small example.

like image 521
SanketS Avatar asked Oct 04 '13 12:10

SanketS


People also ask

What is session management in MVC?

ASP.NET MVC provides three ways (TempData, ViewData and ViewBag) to manage session, apart from that we can use session variable, hidden fields and HTML controls for the same. But like session variable these elements cannot preserve values for all requests; value persistence varies depending the flow of request.

How many types of sessions are there in MVC?

There are four mode types or just modes. In-Process mode, State Server mode, SQL Server mode, Custom mode and Off mode. These are modes.

Where session is stored in MVC?

The session is configured on web. config . By default is saved on memory and a service that runs on server is handle that.


1 Answers

Session management is simple. Session object is available inside MVC controller and in HttpContext.Current.Session. It is the same object. Here is a basic example of how to use Session:

Write

Session["Key"] = new User("Login"); //Save session value

Read

user = Session["Key"] as User; //Get value from session

Answering your question

if (Session["Key"] == null){
   RedirectToAction("Login");
}

Check out Forms Authentication to implement highly secure authentication model.


UPDATE: For newer versions of ASP.NET MVC you should use ASP.NET Identity Framework. Please check out this article.

like image 135
Andrei Avatar answered Oct 26 '22 19:10

Andrei