MVC Form验证登录,操作Cookie
[HttpPost] public ActionResult Login(string txtUserName, string txtPwd) { int expireDays = 3; var ticket = new FormsAuthenticationTicket( 1, "", DateTime.Now, DateTime.Now.AddDays(expireDays), true, "abcdefg-111", FormsAuthentication.FormsCookiePath); var encryptedTicket = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket); cookie.HttpOnly = true; cookie.Secure = FormsAuthentication.RequireSSL; cookie.Path = FormsAuthentication.FormsCookiePath; cookie.Domain = FormsAuthentication.CookieDomain; cookie.Expires = ticket.Expiration; this.Response.Cookies.Add(cookie); return RedirectToAction("Main","Home"); } public ActionResult Main() { var cookie = Request.Cookies[FormsAuthentication.FormsCookieName]; var ticket = FormsAuthentication.Decrypt(cookie.Value); string role = ticket.UserData; return View(); }
--2015-06-02添加新信息,已经测试------------------------------------------------
Web.Config
<authentication mode="Forms"> <forms name=".ASPXAUTH" loginUrl="login.aspx" timeout="30" path="/" requireSSL="false" domain=""> </forms> </authentication> <authorization> <allow users="*"/> </authorization>
Controller
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(30), true, "管理员,会员", "/"); //使用webcongfi中定义的方式,加密序列化票据为字符串 string HashTicket = FormsAuthentication.Encrypt(Ticket); //将加密后的票据转化成cookie HttpCookie UserCookie = new HttpCookie(FormsAuthentication.FormsCookieName, HashTicket); //添加到客户端cookie Response.Cookies.Add(UserCookie);
Page
if (HttpContext.Current.User.Identity.IsAuthenticated) { <a>@User.Identity.Name</a> } else { string a = ""; }
浙公网安备 33010602011771号