【问题标题】:Create Cookie in MVC 3在 MVC 3 中创建 Cookie
【发布时间】:2012-05-14 09:26:22
【问题描述】:

如何一步一步创建 cookie,

当他/她单击记住我时存储用户登录 ID 和密码?选项

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

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-mvc-3


    【解决方案1】:

    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.

    【讨论】:

    • 您好,我有两件事要问....1。如果我们想在视图中看到cookie中存储的数据,那么怎么才能看到或者调用呢?
    • 和 2. 此 cookie 和 FormsAuthentication 票证 cookie 的主要区别是什么?还是两者都一样......?
    • 表单身份验证是一种在 ASP.NET 中对用户进行身份验证的方法。你不必使用它,但它被广泛使用。 “票证”是表单身份验证模块在收到每个请求时解密和验证的加密 cookie。如果票证 cookie 丢失或无效,则不会认为用户已登录。通常,您不必关心 FormsAuth cookie 的内容,只需相信模块正在完成其工作(它做得很好)。我将通过如何阅读 cookie 来改进我的答案。
    • @HackedByChinese,说得好。我刚刚在我的新应用程序中实施了表单身份验证。现在我有了更好的理解。通常,我正在使用 Windows 身份验证创建内部应用程序。
    • @HackedByChinese,还有一件事....在您提供的文章中,Dan Harden 的最后一条评论是“不太清楚那里发生了什么,虽然本教程现在已经很老了,所以事情可能已经改变了. 我能做的就是祝你好运。”是否值得走工单中的自定义数据路由?
    猜你喜欢
    • 2023-04-11
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-18
    相关资源
    最近更新 更多