Session Management in MVC

前端 未结 3 1212
小蘑菇
小蘑菇 2020-12-15 23:19

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

相关标签:
3条回答
  • 2020-12-15 23:38

    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.

    0 讨论(0)
  • 2020-12-15 23:45

    Have you worked on Asp.Net application? Using Forms Authentication you can easily maintain user session.

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

    0 讨论(0)
  • 2020-12-15 23:54

    Here is a Example. Say we want to manage session after checking user validation, so for this demo only I am hard coding checking valid user. On 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 Index Page

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

    On SignOut Button

    Session.Remove("uname");
    return Redirect("~/Account/Login");
    
    0 讨论(0)
提交回复
热议问题