一些概念:Application是所有Session共有的,整个web应用程序唯一的一个对象
Cache是一个全局对象,作用的范围是整个应用程序,所有用户;
Session是一个用户会话对象,是局部对象,用于保存单个用户的信息。
防止重复登录的方法很多 比如用数据库来记录用户登录情况、用Application来保存用户登录信息、用Cache来保存信息等等
1用数据库来记录用户登录情况
在pagebase中判断session["id"]是否为空
空的话重新去数据库中读取:相当于重新登入一次
不为空直接将seeeion["id"]赋值给id
在注销或时间到期时 删除数据库中 用户对应的id
或在global中添加处理
protected void Session_End(object sender, EventArgs e)
{
}
在onint页面中加 进行判断是否当前的seeeion存在
存在说明没有用户用相同账号登入
不存在说明当前账号已经被注销或登入!
public bool Check(string guid)
{
string strSql = "select guid from t_session where guid='"+guid+"'";
if (SqlHelper.ExecuteScalar(SqlHelper.connString, CommandType.Text, strSql, null) != null)
{
return true;
}
else
{
return false;
}
}
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Expo.BLL;
using Expo.Common;
/// <summary>
///管理员所有页面类基础此类
/// </summary>
public class ManagePageBase : System.Web.UI.Page
{
/// <summary>
/// 管理员ID
/// </summary>
protected int AdminId;
/// <summary>
/// 管理登录名
/// </summary>
protected string AdminName;
/// <summary>
/// 管理员真实姓名
/// </summary>
protected string AdminRealName;
protected override void OnInit(EventArgs e)
{
//HttpCookie cookie = (HttpCookie)System.Web.HttpContext.Current.Request.Cookies["User"];
//if (cookie != null)
//{
// Response.Write(cookie.Expires.ToString());
//}
Int32.TryParse(UCookies.Cookie["AdminID"], out AdminId);
if (AdminId > 0)
{
AdminName = UCookies.Cookie["AdminName"];
AdminRealName = UCookies.Cookie["RealName"];
}
else
{
// Response.Redirect("login.aspx");
Response.Write("<script language=\"javascript\">");
Response.Write("var sdt=new Date("+ System.DateTime.Now.Year + "," + System.DateTime.Now.Month + "," + System.DateTime.Now.Day + ");");
Response.Write("d = new Date();");
Response.Write("var cdt=new Date(d.getYear(),d.getMonth(),d.getDate());");
Response.Write("if(sdt!=cdt){alert(\"您电脑系统时间与服务器系统时间相差太多,如果造成您无法登录系统,请更新您的电脑系统时间!\");}");
Response.Write("</script>");
Response.Write("如果看到该信息,可能是您登录超时,请再次<a href=\"login.aspx\">登录</a>,如果连续多次登录不上,请与开发人员联系!");
Response.End();
}
base.OnInit(e);
}
}
//先在数据库中查询帐号密码
//有的情况先 在session表中 插入一条记录
//下次登入 查询session表
//如果已经登入 提示
//否则顺利登入
public int IfHasLog(string username, string userpassword,out string session)
{
string strSql = "Select UserID From userxx Where UserName="+username+" And UserPassword="+userpassword+"";
//判断是否是有效用户登入
object UserID=SqlHelper.ExecuteScalar(SqlHelper.connString, CommandType.Text, strSql, null);
if (UserID != null)
{
//取得随机数
string newid = SqlHelper.ExecuteScalar(SqlHelper.connString, CommandType.Text, "Select newid()", null).ToString();
string id = UserID.ToString();
session = newid;
//是否已经登入
if (SqlHelper.ExecuteScalar(SqlHelper.connString, CommandType.Text, "Select guid from t_session where id=" + id + " ", null) !=null)
{
//已经登入的情况下 删除他目前id的数据
int zz= SqlHelper.ExecuteNonQuery(SqlHelper.connString, CommandType.Text, "delete from t_session where id=" + id + " ", null);
}
//插入一条新的session记录到表中
string InsertSession = "insert into t_session(guid,id) values(@guid,@id)";
SqlParameter[] parameters2 = {
new SqlParameter("@guid", SqlDbType.VarChar,50),
new SqlParameter("@id", SqlDbType.Int,4),
};
parameters2[0].Value = newid;
parameters2[1].Value = id;
if (SqlHelper.ExecuteNonQuery(SqlHelper.connString, CommandType.Text, InsertSession, parameters2)>0)
{
return 1;//插入成功 也即登入成功
}
else
{
return -1;//插入失败
}
}
else
{
session = "";
return -1;//登入失败
}
}
2.Application
实现思路:
用户登录成功后,将用户登录信息存放到Hashtable类型的Application["Online"]里面,其键值为SessionID,其Value值为用户ID;当用户注销时,调用Session.Abandon;在Global.asax里面的SessionEnd事件中,将用户ID从Hashtable中删除;在用户访问页面时,察看Hashtable中是否有对应的用户ID如果没有则判断用户不在线(用户不在线的原因可能是按了注销按钮、网页超时等)
1、公用类中判断用户是否在线的函数(供用户调用)
1/// <summary>
2/// 判断用户strUserID是否包含在Hashtable h中
3/// </summary>
4/// <param name="strUserID"></param>
5/// <param name="h"></param>
6/// <returns></returns>
7public static bool AmIOnline(string strUserID, Hashtable h)
8{
9 if (strUserID == null)
10 return false;
11
12 //继续判断是否该用户已经登陆
13 if (h == null)
14 return false;
15
16 //判断哈希表中是否有该用户
17 IDictionaryEnumerator e1 = h.GetEnumerator();
18 bool flag = false;
19 while (e1.MoveNext())
20 {
21 if (e1.Value.ToString().CompareTo(strUserID) == 0)
22 {
23 flag = true;
24 break;
25 }
26 }
27 return flag;
28}
2、用户登录事件处理:
private void btnlogin_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
//User为自定义的类,其中包含Login方法
User CurUser = new User();
CurUser.UserID = this.username.Text.Trim();
if (MyUtility.AmIOnline(CurUser.UserID, (Hashtable) Application["Online"]))
{
JScript.Alert("您所使用的登录ID已经在线了!您不能重复登录!");
return;
}
CurUser.LoginPsw = FormsAuthentication.HashPasswordForStoringInConfigFile(this.password.Text.Trim(), "SHA1");
int ii = CurUser.Login();
StringBuilder sbPmt = new StringBuilder();
switch (ii)
{
case 0: //如果登录成功,则将UserID加入Application["Online"]中
Hashtable h = (Hashtable) Application["Online"];
if (h == null)
h = new Hashtable();
h[Session.SessionID] = CurUser.UserID;
Application["Online"] = h;
Session["UserID"] = CurUser.UserID;
Session["UserNM"] = CurUser.UserNM;
Session["RoleMap"] = CurUser.RoleMap;
Session["LoginPsw"] = CurUser.LoginPsw;
Session["LoginTime"] = DateTime.Now;
Response.Redirect("ChooseRole.aspx");
break;
case -1:
JScript.Alert("用户名错误!");
break;
case -2:
JScript.Alert("密码错误!");
break;
default:
sbPmt.Append("登录过程中发生未知错误!");
JScript.Alert(sbPmt.ToString());
break;
}
return;
}
3、在Global.asax中的Session_End事件:
protected void Session_End(Object sender, EventArgs e)
{
Hashtable h = (Hashtable) Application["Online"];
if (h[Session.SessionID] != null)
h.Remove(Session.SessionID);
Application["Online"] = h;
}
4、在每一个页面需要刷新的地方,调用如下代码:
try
{
if (!common.MyUtility.AmIOnline(Session["UserID"].ToString(), (Hashtable) Application["OnLine"]))
{
//用户没有在线 ,转到登录界面
Response.Write("<script>parent.document.location.href='Login.aspx';</script>"); ////有框架时用
//Response.Redirect("login.aspx"); ////无框架时用
return;
}
}
catch
{
//会话过期 ,转到登录界面
Response.Write("<script>parent.document.location.href='Login.aspx';</script>"); ////有框架时所用
//Response.Redirect("login.aspx"); ////无框架时用
return;
}
3.Cache
我们都知道Cache与Session这二个状态对像的其中有一个不同之处,Cache是一个全局对象,作用的范围是整个应用程序,所有用户;而Session是一个用户会话对象,是局部对象,用于保存单个用户的信息。
我们只要把每次用户登录后的用户信息存储在Cache中,把Cache的Key名设为用户的登录名,Cache的过期时间设置为Session的超时时间,在用户每次登录的时候去判断一下Cache[用户名]是否有值,如果没有值,证明该用户没有登录,否则该用户已登录。具体实现请看下例:
{
string strUser=string.Empty;
string strCacheKey = this.TextBox1.Text;
strUser = Convert.ToString(Cache[strCacheKey]);
if(strUser == string.Empty)
{
TimeSpan SessTimeOut = new TimeSpan(0,0,System.Web.HttpContext.Current.Session.Timeout,0,0);
Cache.Insert(strCacheKey,strCacheKey,null,DateTime.MaxValue,SessTimeOut,CacheItemPriority.NotRemovable,null);
Session["User"] = strCacheKey;
this.Label1.Text = Session["User"].ToString();
}
else
{
this.Label1.Text = "这个用户已经登录!";
}
}