马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

ASP.NET登陆记住我功能以及验证码

[复制链接]
查看5307 | 回复2 | 2016-6-30 09:42:13 | 显示全部楼层 |阅读模式
转载博客园,此代码未经本人测试。

1,我们在登陆中经常会遇到访问系统的某个页面无法登陆,需要走登陆页面,尽管访问的不是登陆页面,那么这是怎么做的呢?以及在登陆中有记住我以及验证码的输入功能。

今天就写了这么一个demo关于登陆验证 验证码,以及记住我功能呢

2,在这中主要用到了Session 和Cookies,Cookies 存储客户的登陆信息,Session存取验证码信息


登录页:Login.aspx

[HTML] 纯文本查看 复制代码
<script>
 function checkcode() {
 var vcode = document.getElementById("checkcode");
 vcode.src = vcode.src + '1';
 }
 window.onload = function () {
 var did = document.getElementById("width").style.width;
 did = window.innerWidth - 100;
 }
 </script>
 
<form id="form1" runat="server" method="post">
用户名:<input type="text" name="username" value="<%=username %>" />
 <br />
 <br />
密 码:<input type="password" name="upwd" value="<%=upwd %>" />
 <br />
验证码:<input type="text" name="Vcode" />
 <img src="ValidateCode.ashx?1" id="checkcode" />
 <a href="Javascript:checkcode()">看不清,换一张</a>
 <br />
 <br />
 <div id="width">
 <div style="margin: 0 auto">
记住我:<input type="checkbox" name="echeck" />
 </div>
 </div>
 <br />
 <input type="submit" value="登陆" />
 </form>





后台代码:
[C#] 纯文本查看 复制代码
public partial class Login : System.Web.UI.Page
 {
 protected string username { get; set; }
 protected string upwd { get; set; }
 protected void Page_Load(object sender, EventArgs e)
 {
 string vcode=Request["Vcode"];
 //页面第一次加载,如果验证码为空,取缓存
if (string.IsNullOrEmpty(vcode))
 {
 HttpCookie cooike = Request.Cookies["jun"];
 if (cooike!= null) {
 string uinfo = Encoding.UTF8.GetString(Convert.FromBase64String(cooike.Value));
 username = uinfo.Split('_')[0];
 upwd = uinfo.Split('_')[1];
 }
 }
 else {
 if (vcode != null)
 {
 if (vcode.Equals(Session["vcode"].ToString(), StringComparison.CurrentCultureIgnoreCase))
 {
 //验证码正确
string sql = "select count(*) from tb_Userinfo where userName=@uname and userpwd=@upwd";
 SqlParameter[] ps = new SqlParameter[] { 
new SqlParameter("@uname",Request["username"]),
 new SqlParameter("@upwd",Request["upwd"])
 };
 int count = Convert.ToInt32(SqlHelper.ExecuteScalar(sql, ps));
 //用户信息正确
if (count > 0)
 {
 //如果勾中记住我
if (!string.IsNullOrEmpty(Request["echeck"]))
 {
 //登陆成功,存取Cookies信息
string uinfo = Request["username"] + "_" + Request["upwd"];
 //转成64位编码
uinfo = Convert.ToBase64String(Encoding.UTF8.GetBytes(uinfo));
 HttpCookie cooike = new HttpCookie("jun", uinfo)
 {
 Expires = DateTime.Now.AddDays(14)
 };
 Response.Cookies.Add(cooike);
 }
 Session["userinfo"] = 1;
 Response.Redirect("Index.aspx");
 }
 else
 {
 Response.Write("用户名或密码错误");
 }
 }
else
 {
 Response.Write("验证码错误");
 }
 }
 }
 }
 }



成功后转到Index页面  转到页面首先走Index继承的SessionStatus类  我们在这里面封装一个方法
[C#] 纯文本查看 复制代码
protected void p_load(object sender, EventArgs e)
 {
 if (Session["userinfo"] == null) 
{
 Response.Redirect("Login.aspx");
 }
 }



在Login.aspx.cs页面先存储Session["userinfo"]=1 这样就能完成非登陆页验证是否合法登陆了

验证码我主要引用一个一般处理程序:ValidateCode.ashx


[C#] 纯文本查看 复制代码
public void ProcessRequest(HttpContext context)
 {
 context.Response.ContentType = "image/jpeg";
 CreateImage(CreateRandomCode(4)).Save(context.Response.OutputStream, ImageFormat.Jpeg);
 }
 //产生随机码
private string CreateRandomCode(int iLength)
 {
 int rand;
 char code;
 string randomCode = String.Empty;
 
//生成一定长度的验证码
System.Random random = new Random();
 for (int i = 0; i < iLength; i++)
 {
 rand = random.Next();
 if (rand%3==0)
 {
 code = (char)('A' + (char)(rand % 26));
 }
 else
 {
 code = (char)('0'+(char)(rand%10));
 }
 randomCode += code.ToString();
 }
 
Console.WriteLine("--------------------------"+HttpContext.Current.Session.SessionID);
 HttpContext.Current.Session["vcode"] = randomCode;
 return randomCode;
 }
 //创建随机图片
private Image CreateImage(string strVerifyCode)
 {
 Bitmap map;
 try
 {
 int iRandAngle = 45; //随机转动角度
int iMapWidth = (int)(strVerifyCode.Length * 21);
 map = new Bitmap(iMapWidth, 28); //创建图片背景
 
Graphics graph = Graphics.FromImage(map);
 graph.Clear(Color.AliceBlue);//清除画面,填充背景
 
graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;//模式
 

Random rand = new Random();
 
//背景噪点生成
Pen blackPen = new Pen(Color.LightGray, 0);
 for (int i = 0; i < 50; i++)
 {
 int x = rand.Next(0, map.Width);
 int y = rand.Next(0, map.Height);
 graph.DrawRectangle(blackPen, x, y, 1, 1);
 }
 

//验证码旋转,防止机器识别
char[] chars = strVerifyCode.ToCharArray();//拆散字符串成单字符数组
 
//文字距中
StringFormat format = new StringFormat(StringFormatFlags.NoClip);
 format.Alignment = StringAlignment.Center;
 format.LineAlignment = StringAlignment.Center;
 
//定义颜色
Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
 //定义字体
string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
 
for (int i = 0; i < chars.Length; i++)
 {
 int cindex = rand.Next(7);
 int findex = rand.Next(5);
 
Font f = new System.Drawing.Font(font[findex], 13, System.Drawing.FontStyle.Bold);//字体样式(参数2为字体大小)
Brush b = new System.Drawing.SolidBrush(c[cindex]);
 
Point dot = new Point(16, 16);
 
float angle = rand.Next(-iRandAngle, iRandAngle);//转动的度数
 
graph.TranslateTransform(dot.X, dot.Y);//移动光标到指定位置
graph.RotateTransform(angle);
 graph.DrawString(chars[i].ToString(), f, b, 1, 1, format);
 
graph.RotateTransform(-angle);//转回去
graph.TranslateTransform(2, -dot.Y);//移动光标到指定位置
}
 
graph.DrawRectangle(new Pen(Color.Black, 0), -chars.Length * 18, 0, map.Width - 1, map.Height - 1);//画一个边框

}
catch (ArgumentException ex)
 {
 map = null;
 throw ex;
 }
 return map;
 }
 public bool IsReusable
 {
 get
 {
 return false;
 }
 }






C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
ibcadmin | 2016-6-30 09:42:25 | 显示全部楼层
回复是美德
C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
Amy尾巴 | 2016-6-30 10:13:41 | 显示全部楼层
666
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则