gpt4 book ai didi

asp.net - 在 MVC 3 中创建 Cookie

转载 作者:行者123 更新时间:2023-12-04 22:06:56 24 4
gpt4 key购买 nike

我如何一步一步地创建一个 cookie,

当他/她单击“记住我?”时,它会存储用户登录 ID 和密码。选项

我打算在一段时间后杀死这个 cookies

最佳答案

Cookie 的创建方式与在普通旧 ASP.NET 中的创建方式相同,您只需要访问 Response

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

}

您可以像这样读取 cookie:
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();
}

可以解密和读取票证的内容。如果需要,您甚至可以在票证中存储少量自定义数据。 See this article for more info.

关于asp.net - 在 MVC 3 中创建 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10580608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com