mvc4 Forms验证存储 两种登录代码

自己也不知道网上看到的第一种居多,第二种用到的人很少,第二种代码十分简洁,就是不清楚是否有安全隐患。

 

要采用Forms身份验证,先要在应用程序根目录中的Web.config中做相应的设置:

<authentication mode="forms"> 
     <forms name=".ASPXAUTH " loginUrl="/Account/Login"  />
</authentication>

 

1.第一种登录代码

复制代码
        public ActionResult LoginIn(string username,string password) 
        {
            string userdata = username + "|" + password;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, 
                username, 
                DateTime.Now, 
                DateTime.Now.AddHours(1), 
                true, 
                userdata);

            string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            Response.Cookies.Add(authCookie);  

            return RedirectToAction("Index");
        }
复制代码

判断是否登录,取cookie里的登录信息。

复制代码
        public ActionResult Index()
        {
            if (User.Identity.IsAuthenticated)
            {
                string cookieName = FormsAuthentication.FormsCookieName; 
                HttpCookie authCookie = Request.Cookies[cookieName]; 
                FormsAuthenticationTicket authTicket = null; 
                authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                string userinfo = authTicket.UserData;
            }
            
            return View();
        }
复制代码

注销登录,这个两种方法通用。

        public string loginOut() 
        {
            FormsAuthentication.SignOut();
            return "ok";
        }

 

接下来是自己用的第二种登录代码

2.第二种登录代码

        public ActionResult LoginIn(string username, string password)
        {
            string userdata = username + "|" + password;
            FormsAuthentication.SetAuthCookie(userdata,true);

            return RedirectToAction("Index");
        }

判断是否登录,取cookie里的登录信息。

        public ActionResult Index()
        {
            if (User.Identity.IsAuthenticated)
            {
                string userinfo = User.Identity.Name;
            }
            return View();
        }

 

posted @   十二月雨  阅读(671)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
· 使用C#创建一个MCP客户端
点击右上角即可分享
微信分享提示