zoukankan      html  css  js  c++  java
  • 纯手写验证码MVC中

     轻松实现验证码,以此为基础,什么高大上验证码万变不离其中,有注释的喔:-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>
                    }
  • 相关阅读:
    CentOs下Mongodb的下载与安装
    Mysql的sql_mode
    【Android】无限滚动的HorizontalScrollView
    Android 交错 GridView
    Android文档资源大放送 感兴趣的话可以网盘下载(个人收集)
    2014年最新720多套Android源码2.0GB免费一次性打包下载
    安卓开发之刮刮乐实例教程
    Android捕获崩溃异常
    Android -- Messager与Service
    Git的简单使用
  • 原文地址:https://www.cnblogs.com/woloveprogram/p/4683424.html
Copyright © 2011-2022 走看看