Asp.net 在MVC3中创建Cookie
如何一步一步地创建cookie 当用户单击“记住我”时存储用户登录id和密码的?选择权Asp.net 在MVC3中创建Cookie,asp.net,asp.net-mvc,asp.net-mvc-3,Asp.net,Asp.net Mvc,Asp.net Mvc 3,如何一步一步地创建cookie 当用户单击“记住我”时存储用户登录id和密码的?选择权 我计划在一定时间后杀死这个cookie,创建cookie的方法与在普通的旧ASP.NET中相同,您只需要访问响应 public ActionResult Login(string username, string password, bool rememberMe) { // validate username/password
我计划在一定时间后杀死这个cookie,创建cookie的方法与在普通的旧ASP.NET中相同,您只需要访问
响应
public ActionResult Login(string username, string password, bool rememberMe)
{
// validate username/password
if (rememberMe)
{
HttpCookie cookie = new HttpCookie("RememberUsername", username);
Response.Cookies.Add(cookie);
}
return View();
}
但是,如果您使用的是Forms Auth,则只需将FormsAuth票证cookie持久化即可:
public ActionResult Login(string username, string password, bool rememberMe)
{
// validate username/password
FormsAuthentication.SetAuthCookie(username, rememberMe);
return View();
}
您可以像这样阅读cookies:
public ActionResult Index()
{
var cookie = Request.Cookies["RememberUsername"];
var username = cookie == null ? string.Empty : cookie.Value; // if the cookie is not present, 'cookie' will be null. I set the 'username' variable to an empty string if its missing; otherwise i use the cookie value
// do what you wish with the cookie value
return View();
}
public ActionResult Index()
{
var username = User.Identity.IsAuthenticated ? User.Identity.Name : string.Empty;
// do what you wish with user name
return View();
}
如果您使用的是表单身份验证,并且用户已登录,则可以通过以下方式访问他们的用户名:
public ActionResult Index()
{
var cookie = Request.Cookies["RememberUsername"];
var username = cookie == null ? string.Empty : cookie.Value; // if the cookie is not present, 'cookie' will be null. I set the 'username' variable to an empty string if its missing; otherwise i use the cookie value
// do what you wish with the cookie value
return View();
}
public ActionResult Index()
{
var username = User.Identity.IsAuthenticated ? User.Identity.Name : string.Empty;
// do what you wish with user name
return View();
}
可以解密和读取票据的内容。如果需要,您甚至可以在票据中存储少量自定义数据 嗨,我有两件事要问。如果我们想在视图中查看存储在cookie中的数据,那么我们如何查看或调用它。此cookie与FormsAuthentication票证cookie的主要区别是什么?或者两者都相同…?表单身份验证是在ASP.NET中对用户进行身份验证的一种方法。你不必使用它,但它被广泛使用。“票据”是一个加密的cookie,表单身份验证模块在收到每个请求时对其进行解密和验证。如果票据cookie丢失或无效,则认为用户未登录。通常,您不关心FormsAuth cookie的内容,只需相信模块正在完成它的工作(它做得非常好)。“我将通过如何阅读曲奇来改进我的答案。”哈克德比汉语,说得好。我刚刚在我的新应用程序中实现了表单身份验证。现在我有了更好的理解。通常,我是用Windows身份验证创建内部应用程序。@HackedByChinese,还有一件事……在您提供的文章中,Dan Harden的最后一句评论是“不太确定那里发生了什么,尽管本教程已经很老了,所以事情可能已经改变。我所能做的就是祝您好运。”是否值得在票据中使用自定义数据路由?