码迷,mamicode.com
首页 > 其他好文 > 详细

纯手写验证码MVC中

时间:2015-07-28 17:58:26      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

 轻松实现验证码,以此为基础,什么高大上验证码万变不离其中,有注释的喔:-O;

生成验证码
public void Validate() { Random r = new Random(); string str = null; for (int i = 0; i < 5; i++) { int rNumber = r.Next(0, 10); str += rNumber; //随机取0到10之间的5个随机数存入字符串变量str } this.Session["Validate"] = str; //将str写入session Bitmap bmp = new Bitmap(100, 30); //新建一块画布,大小为 宽100 高30 Graphics g = Graphics.FromImage(bmp); //创建一个Graphics 画笔,操作bmp g.Clear(System.Drawing.Color.White); //画布的初始颜色设为白色,初始颜色为黑色; for (int i = 0; i < 5; i++) { Point p = new Point(i * 20, 0); string[] fonts = { "微软雅黑", "宋体", "黑体", "隶书", "仿宋" }; Color[] colors = { Color.Maroon, Color.Blue, Color.Black, Color.Red, Color.Green }; g.DrawString(str[i].ToString(), new Font(fonts[r.Next(0, 5)], 20, FontStyle.Bold), new SolidBrush(colors[r.Next(0, 5)]), p); //以此将5个数字写在画布上 //g.DrawImage(bmp, 1, 1); } for (int i = 0; i < 15; i++) { Point p1 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height)); Point p2 = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height)); //画线 g.DrawLine(new Pen(Brushes.Green), p1, p2); } for (int i = 0; i < 500; i++) { Point p = new Point(r.Next(0, bmp.Width), r.Next(0, bmp.Height));//画点点 bmp.SetPixel(p.X, p.Y, Color.Black); } MemoryStream stream = new MemoryStream(); //保存图片 bmp.Save(stream, ImageFormat.Gif); //保存为.gif数据 base.Response.ClearContent(); base.Response.ContentType = "image/Gif"; base.Response.BinaryWrite(stream.ToArray()); }

 

获取验证码:   

string Validate = this.Session["Validate"].ToString(); //获取写在session内的验证码 string Validate2 = Request["Validate"]; if (Validate == Validate2) //如果 验证码通过, {  ... }
前台:
   @using (Html.BeginForm())
                {   
                    <p class="row-fluid">
                        @Html.Label("验证码:", new { @class = "span4 magino" })
                        @Html.TextBox("Validate")
                        <img src="/Home/Validate" onclick="this.src = ‘/Home/Validate?‘ + Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;" class="span3">
                        
                    </p>
                }

 

纯手写验证码MVC中

标签:

原文地址:http://www.cnblogs.com/woloveprogram/p/4683424.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!