Session Management in MVC

I am new to MVC. I am creating a new WebApplication in MVC4 Razor. I want to save a user login session for all pages. Can someone explain to me how to maintain a session for all views in MVC with a small example.

+8
c # asp.net-mvc asp.net-mvc-4 session-management
source share
3 answers

Session management is easy. The session object is accessible inside the MVC and HttpContext.Current.Session . This is the same object. Here is an example using Session:

To 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"); } 

Forms Authentication opens to implement a highly secure authentication model.


UPDATE: for newer versions of ASP.NET MVC, you must use the ASP.NET Identity Framework. Please read this article .

+17
source share

Have you worked on an Asp.Net application? Using the Form Authentication feature, you can easily maintain a user session.

Find the following links for reference: http://www.codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusF http://msdn.microsoft.com/en-us/library/ff398049(v=vs.100).aspx

+3
source share

Here is an example. Suppose we want to manage a session after validating a user check, so for this demonstration, I only hardcode the validation of a valid user. Account Login

 public ActionResult Login(LoginModel model) { if(model.UserName=="xyz" && model.Password=="xyz") { Session["uname"] = model.UserName; Session.Timeout = 10; return RedirectToAction("Index"); } } 

On the index page

 public ActionResult Index() { if(Session["uname"]==null) { return Redirect("~/Account/Login"); } else { return Content("Welcome " + Session["uname"]); } } 

SignOut Button

 Session.Remove("uname"); return Redirect("~/Account/Login"); 
+3
source share

All Articles