Session详解

•Cookie不能存储过多信息。如果想保存大量的数据,可以保存一个Guid到Cookie中,然后在服务器中建立一个以Guid为Key,复杂数据为Value全局Dictionary。static字段对于不同用户也只有一份,因此用static实现多用户共享数据。代码见备注※。
•ASP.Net已经内置了Session机制,把上面的例子用ASP.NetSession重写。不要放太多的对象到Session,Session会有超时销毁的机制,发帖(服务器不可能知道浏览器是否在开着,什么时候关闭),发帖计时,在线时间统计,靠请求来判断是否活着。Cookie是存在客户端,Session是存在服务器端,目的是一样的:保存和当前客户端相关的数据(当前网站的任何一个页面都能取到Session、Cookie)。不能放太大的数据,放的数据是object。如果禁用了Cookie可以启用Url重写来使用Session,改Web.config。
•可以看到Session机制并不是Http协议规定的,是ASP.net实现的,现在PHP、JSP等大部分服务端技术都实现了Session,原理都差不多。
•Session有自动销毁机制,如果一段时间内浏览器没有和服务器发生任何的交互,则Session会定时销毁。
•案例:Session实现登录,登录以后才能看一些内容。
•先用“动态绘制趣味图片”的例子讲解动态产生图片等内容的原理。
•案例:用Session实现验证码。HttpHandler要能够操作Session,要实现IRequiresSessionState接口。为什么每次点击值都变化?很正常,因为每次页面点击页面都会刷新,就向ashx重新请求图片,ashx的ProcessRequest都会执行。正常网站登录成功就进入主页面,没机会让你看到变化,但是一旦输入错误也是变化。
•点击图片产生新的验证码。 <img src=“YZM.ashx” onclick=“this.src=‘YZM.ashx?aaa=’+new Date()” />每次点击都生成一个新的地址,让浏览器去请求。在AJAX中还会用。

备注※

public class SessionMgr

    {

        private static IDictionary<Guid, IDictionary<string, object>> data = new Dictionary<Guid, IDictionary<string, object>>();

 

        public static IDictionary<string, object> GetSession(GuidsessionId)

        {

            IDictionary<string, object> dict;

 

            if (!data.TryGetValue(sessionId,outdict))

            {

                dict = new Dictionary<string, object>();

                data[sessionId] = dict;

            }

            return dict;

        }

    }

   

设置

            GuidsessionId;

            if (Request.Cookies["MySessionId"] == null)

            {

                sessionId = Guid.NewGuid();

                Response.Cookies.Add(new HttpCookie("MySessionId", sessionId.ToString()));

            }

            else

            {

                sessionId = new Guid(Request.Cookies["MySessionId"].Value);

            }

            SessionMgr.GetSession(sessionId)["用户名"] = TextBox1.Text;

            SessionMgr.GetSession(sessionId)["上次设置时间"] = DateTime.Now;

 

读取

            GuidsessionId;

            if (Request.Cookies["MySessionId"] == null)

            {

                Label1.Text = "错误,还未设置SessionId";

                return;

            }

            else

            {

                sessionId = new Guid(Request.Cookies["MySessionId"].Value);

            }

            var session = SessionMgr.GetSession(sessionId);

            Label1.Text = session["用户名"].ToString() + session["上次设置时间"];

 

验证码

context.Response.ContentType = "image/JPEG";

        using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(100, 50))

        {

            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))

            {

                /*

                g.DrawString("腾迅呀呀", new System.Drawing.Font("宋体", 20), System.Drawing.Brushes.Green, new System.Drawing.PointF(0, 0));

                g.DrawEllipse(System.Drawing.Pens.Red, new System.Drawing.Rectangle(10, 10, 10, 10));

                System.Drawing.Pen pen = (System.Drawing.Pen)System.Drawing.Pens.Red.Clone();

                pen.Width = 3;

                g.DrawEllipse(pen, new System.Drawing.Rectangle(20, 20, 10, 10));

                bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);*/

 

                Random rand = new Random();

                int code = rand.Next(1000,9999);//产生随机验证码

                string strCode = code.ToString();

                //如果要在一般处理程序中操作Session,必须实现IRequiresSessionState接口。

                HttpContext.Current.Session["Code"] = strCode;//将验证码放入Session

                g.DrawString(strCode, new System.Drawing.Font("宋体", 30), System.Drawing.Brushes.Green, new System.Drawing.PointF(0, 0));

                bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);

            }

        }

Session分三种:
1.InProc(进程内)-默认就是这种
--------------------------------------------------------------------------
进程外:可以在IISASPNET服务意外关闭时继续保持状态:
2.StateServer:使用aspnet_state.exe
2.1
修改配置文件:
2.2<sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424"/>
设置是否允许远程使用,位置:C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319
HKEY_LOCAL_MACHINE\SYSTEM\
CurrentControlSet\Services\aspnet_state\Parameters

       2.3默认端口号:42424

       2.4开启服务:我的电脑-管理-服务与应用程序-服务-ASP.NET State Service(ASP.NET 状态服务)

3.SQLServer
3.1
使用aspnet_regsql.exe运行Session数据库脚本:
临时储存区:
InstallSqlState.sql & UninstallSqlState.sql
永久储存区:InstallPersistSqlState.sql & UninstallPersistSqlState.sql(需要使用SQLServerAgent服务-因为调度作业)
注意:之后配置数据库权限麻烦的话,可以在运行完aspnet_regsql.exe后在数据库中执行你想要使用的sql脚本,就可以不配置权限了。
posted on 2013-03-24 10:27  叶龙  阅读(350)  评论(0编辑  收藏  举报