验证码的使用

     以前上网一直难以理解验证码是怎样运作的,电脑怎么能识别图片上的字符呢,这个一直让我很好奇。后来经过了学习,发现验证码其实蛮简单的,但我依旧只了解其中的皮毛,至于内部结构的实现,脑袋里只产生了一点抽象的观念,以至于现在的我只会如何使用验证码,而不知如何去做一个验证码。不过相信以后会理解其中内部结构的实现原理。现在就来写下如何在网站中使用验证码吧!

     先上一段验证码的实现代码,慢慢体会其中的精华:

<%@ WebHandler Language="C#" Class="ValidateCode" %>

using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;

public class ValidateCode : IHttpHandler, IRequiresSessionState
{
    HttpContext context;
    public void ProcessRequest (HttpContext context1) {
        this.context = context1;
        CreateCheckCodeImage(GenerateCheckCode());
    }

    private string GenerateCheckCode()
    {
        int number;
        char code;
        string checkCode = String.Empty;

        System.Random random = new Random();

        for (int i = 0; i < 5; i++)
        {
            number = random.Next();

            if (number % 2 == 0)
                code = (char)('0' + (char)(number % 10));
            else
                code = (char)('0' + (char)(number % 10));
            //code = (char)('A' + (char)(number % 26));

            checkCode += code.ToString();
        }

        //Response.Cookies.Add(new HttpCookie("CheckCode", checkCode));
        context.Session.Add("vCode", checkCode);
        return checkCode;
    }

    private void CreateCheckCodeImage(string checkCode)
    {
        if (checkCode == null || checkCode.Trim() == String.Empty)
            return;

        System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
        Graphics g = Graphics.FromImage(image);

        try
        {
            //生成随机生成器
            Random random = new Random();

            //清空图片背景色
            g.Clear(Color.White);

            //画图片的背景噪音线
            for (int i = 0; i < 25; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }

            Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
            g.DrawString(checkCode, font, brush, 2, 2);

            //画图片的前景噪音点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }

            //画图片的边框线
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            context.Response.ClearContent();
            context.Response.ContentType = "image/Gif";
            context.Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }
    
    public bool IsReusable {
        get {
            return false;
        }
    }

}


切记:这段代码是用后缀为一般处理程序实现的

验证码的使用其实也就是对这段代码的调用,已经封装好了的,当然如果能自己做一个验证码的实现,那是很不错的,废话少说,现在开始进行调用。

调用很简单,在头文件中写下javascript代码,封装一个方法,代码如下:

function getVcode(){

      document.getElementById("img标签的ID").src="vcode.ashx?w="+new Date();

}

下面是html代码

<img id="vcode"  οnclick="getVcode()" src="一般处理程序文件"/>

现在验证码就能显示在网页啦!

在这里当你打开网页的时候验证码实际在session中有了缓存,在网页中建一个文本框,与缓存中的session进行比较,这样一个验证码就实现了!

下面是对输入的验证码的判断正确与否:

     

   //文本框输入的验证码
        string userCode = txtCode.Text.Trim();
        //判断session是否存在,
        if (Session["vCode"] != null)
        {
            //session没有过期
            string sysCode = Session["vCode"].ToString();
            if (sysCode == userCode)
            {
                //验证码输入正确
                Context.Response.Write("恭喜,验证码正确!");
            }
            else
            {
                //验证码输入错误
                Context.Response.Write("对不起,验证码输入错误!");
            }

        }
        else
        {
            //session过期
            Context.Response.Write("验证码以过期!");
        }

具体实例:http://download.csdn.net/detail/lsbairll934723180/5382903
 

      本人菜鸟,写下这篇博客让自己学习,以及对验证码有点模糊的同学给点提示,如有不足,大神勿喷,望留下宝贵意见!

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以给你提供一份简单的代码示例。首先,你需要在前端页面上创建一个发送验证码的按钮,并为其绑定一个点击事件。当用户点击该按钮时,前端将通过 AJAX 请求向后端发送请求,后端会调用阿里云的短信接口来发送验证码。同时,我们需要记录用户发送验证码的时间,以便在5分钟内禁止用户重复发送验证码。 以下是一个简单的代码示例,你可以根据自己的需求进行调整: HTML 代码: ``` <input type="text" id="phone" placeholder="请输入手机号"> <button id="send-code">发送验证码</button> ``` JavaScript 代码: ``` const sendCodeBtn = document.getElementById('send-code'); let lastSendTime = 0; sendCodeBtn.addEventListener('click', () => { const phone = document.getElementById('phone').value; if (!phone) { alert('请输入手机号'); return; } // 判断是否在5分钟内重复发送验证码 const currentTime = Date.now(); if (currentTime - lastSendTime < 5 * 60 * 1000) { alert('请勿重复发送验证码'); return; } // 发送 AJAX 请求,请求后端发送验证码 fetch('/send-code', { method: 'POST', body: JSON.stringify({ phone }), headers: { 'Content-Type': 'application/json' } }) .then(response => response.json()) .then(data => { if (data.code === 0) { alert('验证码已发送,请注意查收'); lastSendTime = currentTime; } else { alert('发送验证码失败'); } }) .catch(e => { console.error(e); alert('发送验证码失败'); }); }); ``` 在上述代码中,我们首先获取用户输入的手机号,并判断是否为空。然后,我们记录了上一次发送验证码的时间,并判断是否在5分钟内重复发送验证码。如果用户满足条件,则会向服务器发送一个 POST 请求,请求服务器发送验证码。在服务器端,我们可以调用阿里云的短信接口来发送验证码。 注意:上述代码仅供参考,你需要根据实际情况进行调整。同时,你需要在后端实现一个 `/send-code` 的 API,用于接收前端发送的请求,并调用阿里云的短信接口来发送验证码

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值