Web.config配置:
在<system.web>节下:
<authentication mode="Forms"> forms loginUrl="~/Auth/Account/Login" timeout="2880" /> </authentication>
登录代码:
/// <summary> /// 登录 </summary> public static bool Login(string userName,string userPwd) { MySqlHelper dbHelper = new MySqlHelper(); sys_user userModel = dbHelper.FindBySql<sys_user>(string.Format("select * from Sys_User where UserName='{0}'",userName)); if (userModel != null) { if (userModel.userPwd.ToUpper() == MD5Helper.Encrypt(userPwd)) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userName,1)">false,120); string encryptedTicket = FormsAuthentication.Encrypt(ticket); HttpCookie authCookie = HttpCookie(FormsAuthentication.FormsCookieName,encryptedTicket); HttpContext.Current.Response.Cookies.Add(authCookie); return true; } } false; }
退出登录代码:
退出登录 void LoginOut() { FormsAuthentication.SignOut(); }
判断用户是否登录:
判断是否登录 bool IsLogin { get { return HttpContext.Current.User.Identity.IsAuthenticated; } }
获取登录用户:
获取登录用户 static sys_user LoginUser { if (HttpContext.Current.User.Identity.IsAuthenticated) { string cookieName = FormsAuthentication.FormsCookieName; HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName]; FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); string userName = authTicket.Name; MySqlHelper dbHelper = MySqlHelper(); return dbHelper.FindBySql<sys_user>(select * from SYS_USER where UserName='{0}'; } }
Action跳过登录验证使用AllowAnonymous:
[AllowAnonymous] public ActionResult Login() { View(); }
需要登录验证的Controller使用Authorize,或者加在自己写的ControllerBase上:
[Authorize] class ControllerBase : Controller
原文地址:https://www.cnblogs.com/s0611163
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。