简体   繁体   English

MVC中的会话管理

[英]Session Management in MVC

I am new in MVC. 我是MVC的新手。 I am creating new WebApplication in MVC4 Razor. 我正在MVC4 Razor中创建新的WebApplication。 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. 任何人都可以用小例子解释如何在MVC中维护所有视图的会话。

Session management is simple. 会话管理很简单。 Session object is available inside MVC controller and in HttpContext.Current.Session . Session对象在MVC控制器和HttpContext.Current.Session可用。 It is the same object. 这是同一个对象。 Here is a basic example of how to use Session: 以下是如何使用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. 查看Forms身份验证以实现高度安全的身份验证模型。


UPDATE: For newer versions of ASP.NET MVC you should use ASP.NET Identity Framework. 更新:对于较新版本的ASP.NET MVC,您应该使用ASP.NET Identity Framework。 Please check out this article . 请查看这篇文章

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 在SignOut按钮上

Session.Remove("uname");
return Redirect("~/Account/Login");

Have you worked on Asp.Net application? 您是否参与过Asp.Net应用程序? Using Forms Authentication you can easily maintain user session. 使用Forms Authentication可以轻松维护用户会话。

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 找到以下给出的链接供您参考: http//www.codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusF http://msdn.microsoft.com/en-us/library/ff398049(v=vs.100)的.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM