public partial class admin : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) { var cookies = Request.Cookies[FormsAuthentication.FormsCookieName]; var ticket = FormsAuthentication.Decrypt(cookies.Value); if(!string.IsNullOrEmpty(ticket.Name)) { Response.Redirect("index.aspx"); } } } catch(Exception ex) { Response.Write(ex.Message); } } protected void btn_submit_Click(object sender, EventArgs e) { try { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, user_name.Text.Trim(), DateTime.Now, DateTime.Now.AddMinutes(20), true, "admin", "/" ); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName,FormsAuthentication.Encrypt(ticket)); cookie.HttpOnly = true; Response.Cookies.Add(cookie); Response.Redirect("index.aspx"); } catch(Exception ex) { Response.Write(ex.Message); } } }
index.aspx.cs
public partial class index : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { if (HttpContext.Current.User.Identity.IsAuthenticated) { if (HttpContext.Current.User.Identity is FormsIdentity) { FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; string userData = ticket.UserData; string[] roles = userData.Split(‘,‘); //此处根据userData解决isInRole返回False的问题 HttpContext.Current.User = new GenericPrincipal(id, roles); Response.Write("管理员" + HttpContext.Current.User.Identity.Name); } } else { Response.Redirect("admin.aspx"); } } catch (Exception ex) { Response.Redirect("admin.aspx"); } ////try ////{ //// if (Request.Cookies[FormsAuthentication.FormsCookieName] != null) //// { //// var cookies = Request.Cookies[FormsAuthentication.FormsCookieName]; //// var ticket = FormsAuthentication.Decrypt(cookies.Value); //// if (!string.IsNullOrEmpty(ticket.Name)) //// { //// Response.Write(ticket.Name); //// } //// else //// { //// Response.Redirect("admin.aspx"); //// } //// } //// else //// { //// Response.Redirect("admin.aspx"); //// } ////} ////catch (Exception ex) ////{ //// Response.Redirect("admin.aspx"); ////} } }
时间: 2024-10-07 05:16:25