12

我是 MVC 的新手。我正在 MVC4 Razor 中创建新的 WebApplication。我想为所有页面维护用户登录会话。任何人都可以用小例子解释我如何维护 MVC 中所有视图的会话。

4

3 回答 3

21

会话管理很简单。Session 对象在 MVC 控制器和HttpContext.Current.Session. 它是同一个对象。以下是如何使用 Session 的基本示例:

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

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

回答你的问题

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

查看Forms Authentication以实现高度安全的身份验证模型。


更新:对于较新版本的 ASP.NET MVC,您应该使用 ASP.NET Identity Framework。请查看这篇文章

于 2013-10-04T12:28:04.567 回答
4

这是一个例子。假设我们想在检查用户验证后管理会话,所以对于这个演示,我只是硬编码检查有效用户。在帐户登录

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

在索引页面上

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

退出按钮

Session.Remove("uname");
return Redirect("~/Account/Login");
于 2014-12-30T14:32:36.463 回答
3

你在 Asp.Net 应用程序上工作过吗?使用表单身份验证,您可以轻松维护用户会话。

找到以下链接供您参考: http: //www.codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusF http://msdn.microsoft.com/en-us/library/ff398049(v=vs.100) .aspx

于 2013-10-04T12:32:33.863 回答