请问各位大哥大姐:
在net框架中,如何实现保持会话?用session、cookie?如果是用cookie,在服务器端又是如何获取客服端的cookie进行验证的?谢谢!!
请问各位大哥大姐:
在net框架中,如何实现保持会话?用session、cookie?如果是用cookie,在服务器端又是如何获取客服端的cookie进行验证的?谢谢!!
验证?
什么意思?
cookie是存在客户端的
在服务器可以取的
你想做什么?
成功登录之后用Session保存会话信息,比如Session["username"] = username;
同时你也可以保存到cookie,退出登录下次登录此网站时用cookie来读取保存的信息,保存cookie:
string pw = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password.Text, "MD5").ToLower().Substring(8, 16); HttpCookie cookie = new HttpCookie("userinfo"); cookie.Values["username"] = username.Text; cookie.Values["password"] = pw; cookie.Expires = DateTime.Now.AddDays(1); Response.AppendCookie(cookie);
密码用MD5加密了。
读取的时候:
if (!IsPostBack) { HttpCookie cookie = Request.Cookies["userinfo"]; if (Request.Cookies["userinfo"] != null) { username.Text = cookie.Values["username"]; password.Text = cookie.Values["password"]; } }
然后点击登录按钮即可登录网站
发个我写的类,和ASP里面读取原理一样.
/// <summary> /// 判断是否登录 /// </summary> /// <returns></returns> public static bool IsLogin() { string CookiesName = ProductCmll.PubLic.GetConfigAppString("CookiesName"); if (HttpContext.Current.Request.Cookies[CookiesName] != null && HttpContext.Current.Request.Cookies[CookiesName].Values["UserName"] != null && HttpContext.Current.Request.Cookies[CookiesName].Values["PassWord"] != null) { string userName = HttpContext.Current.Request.Cookies[CookiesName].Values["UserName"]; string passWord = HttpContext.Current.Request.Cookies[CookiesName].Values["PassWord"]; HttpContext.Current.Session["SiteUserId"] = HttpContext.Current.Request.Cookies[CookiesName].Values["SiteUserId"]; int dealerId = 0; if (HttpContext.Current.Request.Cookies[CookiesName].Values["UserType"] != "0") { Dealer dealer = Dealer.GetByUserId(Convert.ToInt32(HttpContext.Current.Session["SiteUserId"])); if (dealer != null) dealerId = dealer.SiteUserId; } HttpContext.Current.Session["dealerId"] = dealerId;
if (SiteUser.Login(userName, passWord)) return true;
return false; } return false; }