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.
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.
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.
The session is configured on web. config . By default is saved on memory and a service that runs on server is handle that.
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:
Session["Key"] = new User("Login"); //Save session value
user = Session["Key"] as User; //Get value from session
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With