• 绘制验证码


    1.生成验证码字符串

    // 随机生成指定长度的验证码字符串
    private
    string RandomCode(int length) { string s = "0123456789zxcvbnmasdfghjklqwertyuiop"; StringBuilder sb = new StringBuilder(); Random rand = new Random(); int index; for(int i = 0; i < length; i++) { index = rand.Next(0, s.Length); sb.Append(s[index]); } return sb.ToString(); }

     2.绘制干扰线

    private void PaintInterLine(Graphics g,int num,int width,int height)
    {
        Random r = new Random();
        int startX, startY, endX, endY;
        for(int i = 0; i < num; i++)
        {
            startX = r.Next(0, width);
            startY = r.Next(0, height);
            endX = r.Next(0, width);
            endY = r.Next(0, height);
            g.DrawLine(new Pen(Brushes.Red), startX, startY, endX, endY);
        }
    }

    3.生成验证码

    public ActionResult GetValidateCode()
    {
        byte[] data = null;
        string code = RandomCode(5);
        TempData["code"] = code;
        //定义一个画板
        MemoryStream ms = new MemoryStream();
        using(Bitmap map=new Bitmap(100, 40))
        {
            //画笔,在指定画板画板上画图
            //g.Dispose();
            using (Graphics g = Graphics.FromImage(map))
            {
                g.Clear(Color.White);
                g.DrawString(code,new Font("黑体",18.0F),Brushes.Blue,new Point(10,8));
                //绘制干扰线
                PaintInterLine(g, 30, map.Width, map.Height);
            }
            map.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        data = ms.GetBuffer();
        return File(data, "image/jpeg");
    }

    4.前段获取验证码

    <form method="post" id="form1" action="/ValidateCode/login">
        <div class="code">
            <input type="text" name="code" />
            <img id="code" src="/ValidateCode/GetValidateCode/" />
            <a style="text-decoration:none; cursor:pointer" id="chCode">看不清?换一个</a>
        </div>
        <div >
            <input type="submit"  value="登录" />
        </div>
    </form>

     5.后台验证

    public ActionResult Login()
    {
        string code = Request.Form["code"].ToString();
        if (string.IsNullOrEmpty(code))
        {
            return Content("验证输不能为空");
        }
        if (!code.Equals(TempData["code"]))
        {
            return Content("验证输不正确");
        }
        return Content("验证输入正确");
    }
  • 相关阅读:
    C#|.NET从控制反转(依赖注入)想到事件注入 (非AOP)
    libevent 2.1.3 for VS2008 source code
    如何进行object以及Array(数组)的深复制
    Flash ProgressEvent.bytesTotal为0的原因和解决
    Flash字体嵌入方法总结—(4)进阶篇
    mysql分组取每组前几条记录(排名) 附group by与order by的研究
    Flash游戏优化技巧
    教程:深入理解Flash的沙箱 – Application Domains
    Flash Player 11异步解码Bitmap
    常用公式
  • 原文地址:https://www.cnblogs.com/zhuxiang1633/p/7811171.html
Copyright © 2020-2023  润新知