【问题标题】:Session Management in MVCMVC 中的会话管理
【发布时间】:2016-04-27 20:07:29
【问题描述】:

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

【问题讨论】:

  • 是否要在所有页面上显示用户登录信息?

标签: c# .net asp.net-mvc asp.net-mvc-4 session-management


【解决方案1】:

会话管理很简单。会话对象在 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。请查看this article

【讨论】:

  • 我如何检查每个视图的会话。如果会话不存在,那么如何重定向到登录表单。
  • @SanketS:看看 SimpleMembership,它会为你做这一切(并提供使用 [Authorize] 属性的便利)。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      • 2020-12-16
      • 2012-04-30
      • 2010-09-26
      • 2013-12-01
      • 1970-01-01
      相关资源
      最近更新 更多