C# 防止同一个账号多次登录(cache方法)

c#中防止同一账号重复登录的方法有不少,比如用数据库来记录用户登录情况、用Application来保存用户登录信息、用Cache来保存信息等。

本文为大家介绍如何利用缓存Cache方便地实现此功能。 

Cache与Session这二个状态对像的其中有一个不同之处,Cache是一个全局对象,作用的范围是整个应用程序,所有用户;
而Session是一个用户会话对象,是局部对象,用于保存单个用户的信息。 

只要把每次用户登录后的用户信息存储在Cache中,把Cache的Key名设为用户的登录名,Cache的过期时间设置为Session的超时时间,在用户每次登录的时候去判断一下Cache[用户名]是否有值,如果没有值,证明该用户没有登录,否则该用户已登录。

为大家举一个例子吧。

/// <summary>
/// 防止多次登录
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button1_Click(object sender, System.EventArgs e)
{
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 = "这个用户已经登录!";
}
}

大家可以把上面代码用在自己的程序中,检测一下,有效防止同一账号的重复登录。

原文地址:https://www.cnblogs.com/zhangzhixiong/p/4975015.html