<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="piaoju.aspx.cs" Inherits="www.piaoju" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>票据</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="btnShow" runat="server" Text="show" OnClick="btnShow_Click" /> <asp:Button ID="btnGet" runat="server" Text="get" OnClick="btnGet_Click" /> <asp:Button ID="btnSet" runat="server" Text="set" OnClick="btnSet_Click" /> <asp:Button ID="btnLogout" runat="server" Text="out" OnClick="btnLogout_Click" /></div> </form> </body> </html> using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; namespace www { public partial class piaoju : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Bind(); } private void Bind() { //System.Web.Security.FormsAuthentication.SetAuthCookie("111,ttt", false); } protected void btnShow_Click(object sender, EventArgs e) { //Response.Write(System.Web.Security.FormsAuthentication.FormsCookieName); //Response.Write(Request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName].Name); if (IsLogin()) Response.Write("ok"); else Response.Write("no"); } /// <summary> /// 创建一个票据,放在cookie中 /// 票据中的数据经过加密,解决了cookie的安全问题。 /// </summary> /// <param name="username"></param> public void SetCookie(string username,string userData) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(60), false, userData, FormsAuthentication.FormsCookiePath); string encTicket = FormsAuthentication.Encrypt(ticket); HttpCookie newCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket); HttpContext.Current.Response.Cookies.Add(newCookie); } /// <summary> /// 通过此法判断登录 /// </summary> /// <returns>已登录返回true</returns> public bool IsLogin() { return HttpContext.Current.User.Identity.IsAuthenticated; } /// <summary> /// 退出登录 /// </summary> public void Logout() { FormsAuthentication.SignOut(); } /// <summary> /// 取得票据中的数据。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnGet_Click(object sender, EventArgs e) { Response.Write(HttpContext.Current.User.Identity.Name); if (IsLogin()) { string strUserData = ((FormsIdentity)(HttpContext.Current.User.Identity)).Ticket.UserData; Response.Write(strUserData); } } protected void btnSet_Click(object sender, EventArgs e) { if (IsLogin()) { SetCookie("gv","ddddd#12222"); } else { SetCookie("tree","1111#fddd"); } } protected void btnLogout_Click(object sender, EventArgs e) { Logout(); } } }