C# MVC 中的会话管理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19181085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Session Management in MVC
提问by SanketS
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.
我是 MVC 的新手。我正在 MVC4 Razor 中创建新的 WebApplication。我想为所有页面维护用户登录会话。任何人都可以用小例子解释我如何为MVC中的所有视图维护会话。
采纳答案by Andrei
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:
会话管理很简单。会话对象在 MVC 控制器和HttpContext.Current.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 Authenticationto 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.
更新:对于较新版本的 ASP.NET MVC,您应该使用 ASP.NET Identity Framework。请查看这篇文章。
回答by Mak
Have you worked on Asp.Net application? Using Forms Authentication you can easily maintain user session.
您是否曾从事过 Asp.Net 应用程序?使用表单身份验证,您可以轻松维护用户会话。
Find the below given links for your reference: http://www.codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusFhttp://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
回答by Vedprakash_Comp
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");