Session详解
备注※
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);
}
}
1.InProc(进程内)-默认就是这种
--------------------------------------------------------------------------
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.1使用aspnet_regsql.exe运行Session数据库脚本:
临时储存区:InstallSqlState.sql & UninstallSqlState.sql
永久储存区:InstallPersistSqlState.sql & UninstallPersistSqlState.sql(需要使用SQLServerAgent服务-因为调度作业)