Welcome 微信登录

首页 / 网页编程 / ASP.NET / Session服务器配置指南与使用经验

Session服务器配置指南与使用经验2011-08-28 博客园 ziqiu.zhang一.摘要

所有Web程序都会使用Session保存数据. 使用独立的Session服务器可以解决 负载均衡场景中的Session共享问题.本文介绍.NET平台下建立Session服务器的几 种办法, 并介绍在使用Session时的各种经验和技巧.

二.关于Session,SessionID和Cookies

Session数据保存在服务器端, 但是每一个客户端都需要保存一个SessionID, SessionID保存在Cookies中, 关闭浏览器时过期.

在向服务器发送的HTTP请求中会包含SessionID, 服务器端根据SessionID获取 获取此用户的Session信息.

很多初级开发人员不知道SessionID和Cookies的关系, 所以常常认为两者没有 联系. 这是不正确的. 正是因为SessionID保存在Cookies中, 所以在我们保存 Cookies的时候,一定要注意不要因为Cookies的大小和个数问题而导致SessionID 对象. 在我们的程序中, 对SessionID的Cookies有特殊的处理:

/// <summary>
/// 写入cookie.
/// </summary>
/// <param name="day"></param>
/// <returns></returns>
public bool SetCookie(int day)
{
string CookieName = GetType ().ToString();
HttpCookie SessionCookie = null;

//对 SessionId 进行备份.
if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null)
{
string SesssionId = HttpContext.Current.Request.Cookies ["ASP.NET_SessionId"].Value.ToString();
SessionCookie = new HttpCookie("ASP.NET_SessionId");
SessionCookie.Value = SesssionId;

}

//省略掉中间的代码部分.只保留备份SessionID和找回SessionID的逻 辑



//如果cookie总数超过20 个, 重写ASP.NET_SessionId, 以防Session 丢失.
if (HttpContext.Current.Request.Cookies.Count > 20 && SessionCookie != null)
{
if (SessionCookie.Value != string.Empty)
{
HttpContext.Current.Response.Cookies.Remove ("ASP.NET_SessionId");
HttpContext.Current.Response.Cookies.Add(SessionCookie);
}
}

return true;
}