【代码备份】使用Application变量实现同账号、同IP登录次数限制

一、解决问题:

在服务器A上登录失败超过五次,则提示账号冻结,但是在服务器B上也提示此消息问题。

二、解决思路:

1、定义一个记录登录失败次数的变量;

2、以“N_USERID_IP”形式存储在Application变量;

3、若登录失败超过5次则提示账号冻结;

4、若登录成功则Application变量重置为0。

 

三、解决方法:

1、定义一个记录登录失败次数的变量iperrornum

1  int iperrornum = 0;
2  string name1 = "N_" + userid + "_" + GetIpAddress(context);
3  HttpContext.Current.Application.Add(name1, iperrornum);
4  iperrornum = p.ext_int(HttpContext.Current.Application[name1].ToString());

 

2、若登录失败,iperrornum加1,并以“N_USERID_IP”形式存储在Application变量中

 1 object obj = HttpContext.Current.Application.Get(name1);
 2  if (obj == null)
 3    {
 4         // 不存在,直接添加
 5         HttpContext.Current.Application.Add(name1, iperrornum);
 6    }
 7   else
 8     {
 9         iperrornum++;
10        // 存在,不能直接调用 Add 方法,这样会造成两个相同 name 的条目               
11         HttpContext.Current.Application[name1] = iperrornum;
12   }
13   // 用 [] 取值时,等同于 Get 方法
14 HttpContext.Current.Application.Add("N_" + userid + "_" + GetIpAddress(context), iperrornum);

3、若登录成功,则重置Application变量为0

 1 HttpContext.Current.Application[name1] = 0;//缓存重置为0 

 

4、获取用户的客户端IP地址

 1 private string GetIpAddress(HttpContext context)
 2     {
 3         //throw new NotImplementedException();
 4         if (context.Request.ServerVariables["HTTP_VIA"] != null)
 5         {
 6             //客户端使用的是代理服务器
 7             return context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
 8         }
 9         else
10         {
11             //客户端未使用代理服务器
12             return context.Request.ServerVariables["REMOTE_ADDR"].ToString();
13         }
14         //return "localhost";
15     }

 

posted @ 2020-03-31 11:29  橙子819  阅读(232)  评论(0编辑  收藏  举报