1 Cookie的设置和获取:
默认浏览器关闭,cookie就消失,设置有效期,就到期后才消失
cookie与浏览器相关,各种浏览器、同一浏览器窗口、小号模式,互不影响,各有一套cookie
cookie中不能存太多数据、不能存铭感的不能修改password的数据
cookie有可能提前消失,浏览器可以进行瘦身,或用户手动清楚cookie
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class cookie1 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //设置cookie HttpCookie cookie = new HttpCookie("test"); //cookie.Value = "rupeng.com"; cookie.Value = context.Request.UserAgent; //设置有效期,如果没有,则浏览器关闭就消失 cookie.Expires = DateTime.Now.AddSeconds(10); context.Response.SetCookie(cookie); } public bool IsReusable { get { return false; } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class cookie2 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //获取cookie HttpCookie cookie = context.Request.Cookies["test"]; context.Response.Write(cookie==null?"没有这个cookie":cookie.Value); //修改cookie的值 //if(cookie!=null) //{ // cookie.Value = "Core就是必须学"; // context.Response.SetCookie(cookie); //} } public bool IsReusable { get { return false; } } }
2 Cookie实现记住登录用户名:
当用户进入登录界面时,如果cookie中记住了用户名 就自动填充用户名,否则不填
当用户登录时,如果登录成功 就在cookie中记住用户名,否则跳转登录界面
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class memoryUsername : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string login = context.Request["login"]; if(string.IsNullOrWhiteSpace(login)) //展示 { string html = CommonHelper.GetHtmlFromVirtualPath(context, "~/Day4/memoryUsername.html"); //展示时,先从cookie中查看是否有username,如果有就自动显示出用户名,如果没有就不显示 HttpCookie cookieUserName = context.Request.Cookies["LastUserName"]; if (cookieUserName != null) { string cookieValue = cookieUserName.Value; html = html.Replace("@username", cookieValue); context.Response.Write(html); } else { html = html.Replace("@username", ""); context.Response.Write(html); } } else //登录 { //登录时,如果登录成功,不管有没有这个cookie,都重新设置cookie string username = context.Request["username"]; string password = context.Request["password"]; if (username == "admin" && password == "123") //登录成功 { HttpCookie cookieUserName = new HttpCookie("LastUserName"); cookieUserName.Value = username; cookieUserName.Expires = DateTime.Now.AddDays(7); context.Response.SetCookie(cookieUserName); context.Response.Write("登录成功"); } else { context.Response.Redirect("memoryUsername.ashx"); } } } public bool IsReusable { get { return false; } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<body> <form action="memoryUsername.ashx" method="post"> 用户名:<input type="text" name="username" value="@username" /><br /> 密码:<input type="password" name="password" /><br /> <input type="submit" name="login" value="登录" /><br /> </form> </body>
3 Cookie中的Path路径:
cookie.Path 如果不设置,默认是\,表示当前域名下的所有页面都可以读取这个cookie,www.rupeng.com和www.rupeng.cn是2个不同的域名,cookie不共用。
cookie.Path="/Day4/cookiePath1.ashx" 设置path,表示只有这有这个‘/Day4/cookiePath1.ashx’页面,才可以读取这个cookie,否则不能读取不到这个cookie。
cookie.Domain="rupeng.com" 设置cookie的域名,则不管是www.rupeng.com还是bbs.rupeng.com都可以读取到这个cookie。cookie与域名有关。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class cookiePath1 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; HttpCookie cookieRead = context.Request.Cookies["path"]; context.Response.Write(cookieRead == null ? "没有这个cookie" : cookieRead.Value+"||"+cookieRead.Path); //设置cookie HttpCookie cookie = new HttpCookie("path"); cookie.Value = "rupeng.com"; cookie.Expires = DateTime.Now.AddDays(1); cookie.Path = "/Day4/cookiePath1.ashx"; //只有cookiePath1.ashx才能访问这个cookie,因为这个cookie设置在了这个页面 //cookie.Domain = ".rupeng.com"; //把这个cookie设置在了这个域名 www.rupeng.com和bbs.rupeng.com是同一个域名下的2个不同网站,其cookie如果不设置,是不共用的 context.Response.SetCookie(cookie); } public bool IsReusable { get { return false; } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class cookiePath2 : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //读取cookie HttpCookie cookie = context.Request.Cookies["path"]; context.Response.Write(cookie == null ? "没有cookie" : cookie.Value + "||" + cookie.Path); } public bool IsReusable { get { return false; } } }
4 Session的写入和读取,以及判断登录用户是否有权限
session存在服务器,用一个无法被篡改的“身份证号”的sessionId唯一标示。
session必须实现IRequiresSessionState接口,但是会影响性能。
cookie只能存字符串,session几乎可以存任意类型。
session与cookie相关,默认也是浏览器关闭就消失,可以通过<sessionState timeout="20" />在web.config中设置超时时间20分钟。(超时没效果)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class session1 : IHttpHandler,IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //写入session context.Session["session1"] = "ruepng.com"; context.Session["session2"] = 888; } public bool IsReusable { get { return false; } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class session2 : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; object session1 = context.Session["session1"]; //string类型 object session2 = context.Session["session2"]; //int类型 context.Response.Write(session1 == null ? "没有这个session" : session1.ToString()); context.Response.Write(session2 == null ? "没有这个session2" :session2); } public bool IsReusable { get { return false; } } }
判断登录用户是否有权限
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string login = context.Request["login"]; string html = CommonHelper.GetHtmlFromVirtualPath(context, "~/Day4/sessionUserName.html"); #region 展示 if (string.IsNullOrWhiteSpace(login)) //展示 { HttpCookie cookieUserName = context.Request.Cookies["LastUserName"]; if (cookieUserName != null) { html = html.Replace("@username", cookieUserName.Value); context.Response.Write(html); } else { html = html.Replace("@username", ""); context.Response.Write(html); } } #endregion #region 登录 else //登录 { string username = context.Request["username"]; string password = context.Request["password"]; if (password == "123") //为了方便后面的权限判断 username是否为admin,所以这里没注明 { //写入cookie 方便下次登录时自动填充 HttpCookie cookie = new HttpCookie("LastUserName"); cookie.Value = username; cookie.Expires = DateTime.Now.AddDays(7); context.Response.SetCookie(cookie); //写入session 方便后面权限判断 context.Session["LastUserName"] = username; //与cookie相关,默认也是关闭浏览器就消失 } else { //登录失败 context.Response.Redirect("sessionUserName.ashx"); } } #endregion } public bool IsReusable { get { return false; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<body> <form action="sessionUserName.ashx" method="post"> 用户名<input type="text" name="username" value="@username" /><br /> 密码<input type="password" name="password" value="" /><br /> <input type="submit" name="login" value="登录" /><br /> </form> </body>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class sessionUserName1 : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //从session中判断是否有访问权限 object sessionUserName = context.Session["LastUserName"]; if (sessionUserName!=null && sessionUserName.ToString() == "admin") //假设登录user为admin就有权限 { context.Response.Write("可以继续这个页面"); } else { context.Response.Write("该用户未登录或者没有权限"); } } public bool IsReusable { get { return false; } } }
5 实现登录后 返回进入登录的页面
登录时把username存入session中,进入其他页面时判断该sessionId是否为null。
要想登录后跳转以前的页面,需要在以前的页面把url存入session。
要想注销退出登录,需要Abandon()。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using Console_Core.BLL; using Console_Core.Common; using Console_Core.Model; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; namespace Web_Cassini.Day4.SessionCase { /// <summary> /// lojin 的摘要说明 /// </summary> public class lojin : IHttpHandler,IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string login = context.Request["login"]; string html = CommonHelper.GetHtmlFromVirtualPath(context, "~/Day4/SessionCase/lojin.html"); if(string.IsNullOrWhiteSpace(login)) //展示 { html = html.Replace("@username", "").Replace("@password", "").Replace("{msg}", ""); context.Response.Write(html); } else //登录 { string username = context.Request["username"]; string password = context.Request["password"]; //根据username判断 List<object> list = new MyORM_BLL().SelectModelByField(typeof(TC_STUDENT), "USERNAME='" + username + "'"); if (list.Count <= 0) //登录失败 { html = html.Replace("@username", "").Replace("@password", "").Replace("{msg}", "用户名不存在"); context.Response.Write(html); } else if (list.Count == 1) //成功 { context.Session[MySessionClass.LOGINUSERNAME] = username; //context.Response.Redirect("modifypwd.ashx"); //context.Response.Redirect("queryyue.ashx"); string LoginBeforeUrl = (string)context.Session[MySessionClass.LOGINBEFOREURL]; if (LoginBeforeUrl != null) { context.Response.Redirect(LoginBeforeUrl); } else { context.Response.Write("登录成功"); } } else { throw new Exception("内部服务器出错:存在重复的username="+username+"的数据"); } } } public bool IsReusable { get { return false; } } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<body> <form action="lojin.ashx" method="post"> 用户名<input type="text" name="username" value="@username" /><span>{msg}</span><br /> 密码<input type="password" name="password" value="@password" /><br /> <input type="submit" name="login" value="登录" /><br /> </form> </body>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; namespace Web_Cassini.Day4.SessionCase { /// <summary> /// modifypwd 的摘要说明 /// </summary> public class modifypwd : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string username = (string)context.Session[MySessionClass.LOGINUSERNAME]; if (username != null) { context.Response.Write("Hello World 修改密码:" + username + " ......<a href=\"exit.ashx\">退出登录</a>"); } else { //为了使登录成功后,返回之间进入的页面,需要把之前的url存入session中 context.Session[MySessionClass.LOGINBEFOREURL] = context.Request.Url.ToString(); context.Response.Redirect("lojin.ashx"); } } public bool IsReusable { get { return false; } } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; namespace Web_Cassini.Day4.SessionCase { /// <summary> /// queryyue 的摘要说明 /// </summary> public class queryyue : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/html"; string username = (string)context.Session[MySessionClass.LOGINUSERNAME]; if (username != null) { context.Response.Write("Hello World 查询余额:" + username+" ......<a href=\"exit.ashx\">退出登录</a>"); } else { context.Session[MySessionClass.LOGINBEFOREURL] = context.Request.Url.ToString(); context.Response.Redirect("lojin.ashx"); } } public bool IsReusable { get { return false; } } } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; namespace Web_Cassini.Day4.SessionCase { /// <summary> /// eixt 的摘要说明 /// </summary> public class exit : IHttpHandler, IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; context.Session.Abandon(); context.Response.Redirect("lojin.ashx"); } public bool IsReusable { get { return false; } } } }
6 验证码
要想生成验证码,需要生成一个图片保存到输出流(即显示到页面),并使它可以被刷新。
要想验证验证码,需要在生成时存入session,在登录时判断输出的验证码是否与session中验证码相同,如果不同就是验证失败。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg"; Random dom = new Random(); int num = dom.Next(1000, 10000); string code = num.ToString(); context.Session[MySessionClass.VOLIDECODE] = code; using (Bitmap map = new Bitmap(60, 20)) { using (Graphics g = Graphics.FromImage(map)) using (Font font = new Font(FontFamily.GenericSerif, 15)) { g.DrawString(code, font, Brushes.Red, 0, 0); } map.Save(context.Response.OutputStream, ImageFormat.Jpeg); } }
登录验证时的主要代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//验证 验证码 string volidcode=context.Request["volidcode"]; string volidcodeInSesion = (string)context.Session[MySessionClass.VOLIDECODE]; if (volidcode!=volidcodeInSesion) { html = html.Replace("{msg}", "验证码错误"); context.Response.Write(html); return; }
7 session根本原理:
自己写的session--> YangGuoSessionID
初始化YangGuoSessionID.cs时,判断cookie中是否有YangGuoSessionID,如果有就获得sessionId的值,如果没有就创建一个sessionId并获得值;
当设值(写入)时,就是把值写入sessionId所表示的文件中;
当取值(读取)时,就是去除当前sessionId文件中的值。
同时,为了使自定义的YangGuoSessionID可以写入多个值,可以将需要写入的内容以键值对的形式序列化到文件中;读取时,从文件中反序列化为键值对。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Web; namespace Web_Cassini.Day4.SessionCase { public class YangGuoSessionID { public const string YANGGUOSESSIONID = "YangGuoSessionID"; private HttpContext context; private string sessionId; public YangGuoSessionID(HttpContext context) { this.context = context; GetYangGuoSessionID(); } /// <summary> /// 创建自定义sessionId /// </summary> /// <returns>返回自定义cookie的值</returns> private string CreateYangGuoSessionID() { Guid guid = Guid.NewGuid(); HttpCookie cookie = new HttpCookie(YANGGUOSESSIONID); cookie.Value = guid.ToString(); context.Response.SetCookie(cookie); return cookie.Value; } /// <summary> /// 获得YangGuoSessionID /// </summary> /// <returns>返回YangGuoSessionID的值</returns> public void GetYangGuoSessionID() { HttpCookie cookie = context.Request.Cookies[YANGGUOSESSIONID]; if (cookie == null) //判断cookie中是否有YangGuoSessionID,没有就创建,有就获得 { this.sessionId = CreateYangGuoSessionID(); } else { this.sessionId = cookie.Value; } } /// <summary> /// 设置自定义sessionId中的name的value /// </summary> /// <param name="name">需要保存的name</param> /// <param name="value">需要保存的对应name的value</param> public void SetValue(string name, string value) { string path = context.Server.MapPath("~/Day4/SessionCase/" + this.sessionId); Dictionary<string, string> dict = new Dictionary<string, string>(); BinaryFormatter bf = new BinaryFormatter(); if (File.Exists(path)) { //先将文件中的内容反序列化为键值对 dict = Deserialize(path); } //更新键值对后 dict[name] = value; //再序列化到文件中 using (Stream s = File.OpenWrite(path)) { bf.Serialize(s, dict); } } /// <summary> /// 获得自定义的sessionId的对应name的值 /// </summary> /// <param name="name">需要查询的name</param> /// <returns>sessionId对应文件中对应name的value</returns> public string GetValue(string name) { string path = context.Server.MapPath("~/Day4/SessionCase/" + this.sessionId); if (File.Exists(path)) { //先将文件中的内容反序列化为键值对 Dictionary<string, string> dict = Deserialize(path); if (dict.ContainsKey(name)) { return dict[name]; } else { return null; } } else { return null; } } /// <summary> /// 将路径path中内容反序列化为键值对 /// </summary> /// <param name="path">w=文件路径</param> /// <returns>键值对</returns> public Dictionary<string, string> Deserialize(string path) { //先将文件中的内容反序列化为键值对 BinaryFormatter bf = new BinaryFormatter(); using (Stream s = File.OpenRead(path)) { return (Dictionary<string, string>)bf.Deserialize(s); } } ///// <summary> ///// 设置session的值时,把值保存到sesionId对应的文件 ///// </summary> ///// <param name="value">要设置的session的值</param> //public void SetValue(string value) //{ // string path = context.Server.MapPath("~/Day4/SessionCase/" + this.sessionId); // File.WriteAllText(path, value); //} ///// <summary> ///// 获得session的值 ///// </summary> ///// <returns>从sessionId对应文件中获得的值</returns> //public string GetValue() //{ // string path = context.Server.MapPath("~/Day4/SessionCase/" + this.sessionId); // if (File.Exists(path)) // { // return File.ReadAllText(path); // } // else // { // return null; // } //} } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; //写入session YangGuoSessionID ygsesion = new YangGuoSessionID(context); //ygsesion.SetValue("yangguo"); ygsesion.SetValue("username", "yzk"); ygsesion.SetValue("时间", DateTime.Now.ToString()); }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; YangGuoSessionID ygsession = new YangGuoSessionID(context); //string str = ygsession.GetValue(); //context.Response.Write(str); string username =ygsession.GetValue("username"); string date = ygsession.GetValue("时间"); context.Response.Write(username + "===" + date); }
8 配置进程外Session:
(1)将服务器Session信息存储在进程外
<1> 首
先,开启asp.net state 服务: 控制面板 -> 程序和功能 -> “打开或者关闭 Windows 功能”对话框
-> Internet 信息服务 -> 万维网服务 -> 应用程序开发功能 -> ASP.NET。(Control
Panel -> Programs - > Programs and Features -> Turn Windows
features on or off - > Internet Information Services -> World Wide
Web Services -> Application Development Features -> ASP.NET。)
勾选 ASP.NET 选项后,在 Control Panel -> System and Security -> Administrative Tools -> Services 服务中就会出现 ASP.NET State Service 服务。
在属性对话框中设置启动类型为自动(Automatic),最后启动。(备注:Windows XP 系统是在控制面板中的“添加和删除程序”中设置)
<2> 然后,回到Web.config文件中上述的段落中,将mode的值改为StateServer。
<sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" timeout="20"></sessionState>
保存文件后的重新打开一个IE,打开
SessionState.aspx页面,保存一些信息到Session中。这时,让我们重起IIS,再回到SessionState.aspx页面中查
看刚才的Session信息,发现没有丢失。
实际上,这种将Session信息存储在进程外的方式不光指可以将信息存储在本机的进程外,还可以将Session信息存储在其他的服务器的进程中。
这时,不光需要将mode的值改为StateServer,还需要在stateConnectionString中配置相应的参数。例如你的计算你是
192.168.0.1,你想把Session存储在IP为192.168.0.2的计算机的进程中,就需要设置成这
样:stateConnectionString="tcpip=192.168.0.2:42424"。当然,不要忘记在192.168.0.2的计算
机中装上.NET Framework,并且启动ASP.NET State Services服务。
(2)将服务器Session信息存储在SQL Server中
<1>首先,还是让我们来做一些准备工作。启动SQL Server和SQL Server代理服务。在SQL
Server中执行一个叫做InstallSqlState.sql的脚本文件。这个脚本文件将在SQL
Server中创建一个用来专门存储Session信息的数据库,及一个维护Session信息数据库的SQL
Server代理作业。我们可以在以下路径中找到那个文件:
[system drive]\winnt\Microsoft.NET\Framework\[version]\
然后打开查询分析器,连接到SQL
Server服务器,打开刚才的那个文件并且执行。稍等片刻,数据库及作业就建立好了。这时,你可以打开企业管理器,看到新增了一个叫ASPState的
数据库。但是这个数据库中只是些存储过程,没有用户表。实际上Session信息是存储在了tempdb数据库的
ASPStateTempSessions表中的,另外一个ASPStateTempApplications表存储了ASP中Application对
象信息。这两个表也是刚才的那个脚本建立的。另外查看管理->SQL
Server代理->作业,发现也多了一个叫做ASPState_Job_DeleteExpiredSessions的作业,这个作业实际上就是
每分钟去ASPStateTempSessions表中删除过期的Session信息的。
<2>接着,我们返回到Web.config文件,修改mode的值改为SQLServer。注意,还要同时修改sqlConnectionString的值,格式为:
sqlConnectionString="data source=localhost; Integrated Security=SSPI;"
其中data source是指SQL Server服务器的IP地址,如果SQL
Server与IIS是一台机子,写127.0.0.1就行了。Integrated
Security=SSPI的意思是使用Windows集成身份验证,这样,访问数据库将以ASP.NET的身份进行,通过如此配置,能够获得比使用
userid=sa;password=口令的SQL Server验证方式更好的安全性。当然,如果SQL
Server运行于另一台计算机上,你可能会需要通过Active Directory域的方式来维护两边验证的一致性。
同样,让我们做个试验。向SessionState.aspx中添加Session信息,这时发现Session信息已经存在SQL
Server中了,即使你重起计算机,刚才的Session信息也不会丢失。现在,你已经完全看见了Session信息到底是什么样子的了,而且又是存储
在SQL Server中的,能干什么就看你的发挥了