当前位置: 代码网 > it编程>编程语言>Asp.net > ASP.NET实现图形验证码功能

ASP.NET实现图形验证码功能

2024年05月15日 Asp.net 我要评论
asp.net 实现图形验证码能够增强网站安全性,防止机器人攻击。通过生成随机验证码并将其绘制成图像,用户在输入验证码时增加了人机交互的难度。本文介绍了如何使用 c# 和 asp.net 创建一个简单

asp.net 实现图形验证码能够增强网站安全性,防止机器人攻击。通过生成随机验证码并将其绘制成图像,用户在输入验证码时增加了人机交互的难度。本文介绍了如何使用 c# 和 asp.net 创建一个简单而有效的图形验证码系统,包括生成随机验证码、绘制验证码图像以及将图像输出到客户端等步骤。这种验证码系统对于保护网站免受恶意攻击和机器人恶意行为具有重要意义。

一、实现思路 

我们需要实现一个防爬虫的可以动态刷新的随机验证码图片。
比如下面这种:

关键点:

  • 动态:每次打开页面验证码是变化的,并且验证码在一些事件下会自发刷新成新的验证码,比如在点击、输入错误、页面停靠超时等事件触发时,验证码自动刷新。
  • 随机:里面的数字和字母是随机的,是一种强密码,不容易被暴力破解。
  • 防爬:防止爬虫通过一些ai识别直接通过,我们需要增加图片的复杂度,例如添加一些干扰性的图案,包括但不限于噪音线、噪点等。

验证码生成成功后,我们还需要将验证码保存到 session 中,以便后续验证。

二、编写前端代码

思路已经明确,下面,我们来构建图形验证码的前端代码。
前端代码包含 html 和 javascript 代码。

1、编写html代码

html代码包含一个简单的验证码输入框和刷新图片按钮的用户界面:

<div class="checkcode">
    <input type="text" runat="server" id="vercodetext" placeholder="验证码" maxlength="4">
    <img onclick="changepic(this)" src="/handlers/vercode.ashx" />
</div>
  • <div class="checkcode">:创建一个包含验证码元素的 div 容器,用于样式控制。
  • <input type="text" runat="server" id="vercodetext" placeholder="验证码" maxlength="4">:添加一个文本输入框,用于用户输入验证码。设置了id为 "vercodetext",最大长度为4,同时提供了占位符 "验证码"。
  • <img οnclick="changepic(this)" src="/handlers/vercode.ashx" />:插入一个图片元素,其 src 属性指向验证码处理器 vercode.ashx。当用户点击该图片时,触发javascript函数 changepic 进行验证码图像的刷新。

通过这样的html结构,用户可以在输入框中输入验证码,并通过点击图片刷新验证码图像,提供了一种交互式的验证码体验。

2、创建javascript函数

创建 changepic 函数方法:

function changepic(obj) {
    var timestamp = (new date().gettime()) / 1000;
    $(obj).attr('src', 'vercode.ashx?tims=' + timestamp);
}

changepic 函数用于刷新验证码图片,通过在 url 中添加时间戳的方式,确保每次请求都是唯一的,避免浏览器缓存。

三、编写后端代码

后端代码我们采用c#实现。 

1、创建输出图形验证码的接口

创建c#验证码处理器 vercode.ashx:

using carrental.common;
using system;
using system.drawing;
using system.io;
using system.web;
namespace handlers
{
    public class vercode : ihttphandler, system.web.sessionstate.irequiressessionstate
    {
        public void processrequest(httpcontext context)
        {
        }
        public bool isreusable
        {
            get
            {
                return false;
            }
        }
    }
}

vercode 类实现了 ihttphandler 接口,用于处理 http 请求。

2、创建验证码生成方法

/// <summary>
/// 随机构建验证码方法
/// </summary>
/// <returns>返回验证码字符串</returns>
public string createcode()
{
    char code;
    string checkcode = string.empty;
    random rd = new random();
    for (int i = 0; i < 4; i++)
    {
        int num = rd.next();
        int _temp;
        if (num % 2 == 0)
        {
            _temp = ('0' + (char)(num % 10));
            if (_temp == 48 || _temp == 49)
            {
                _temp += rd.next(2, 9);
            }
        }
        else
        {
            _temp = ('a' + (char)(num % 10));
            if (rd.next(0, 2) == 0)
            {
                _temp = (char)(_temp + 32);
            }
            if (_temp == 66 || _temp == 73 || _temp == 79 || _temp == 108 || _temp == 111)
            {
                _temp++;
            }
        }
        code = (char)_temp;
        checkcode += code;
    }
    return checkcode;
}

createcode 方法用于生成随机验证码,包含数字和字母,并进行了一些特殊字符的处理,以增加验证码的复杂性。

3、 绘制验证码图片

① 配置验证码参数

我们先定义验证码图像的宽度、高度、字体大小以及用于生成随机数的 random 对象。

int codeweight = 80;
int codeheight = 22;
int fontsize = 16;
random rd = new random();

② 生成验证码字符串

这一步很简单,我们直接调用之前写好的 createcode 方法。

string checkcode = createcode();

③ 构建验证码背景

创建一个位图对象,并在其上创建图形对象,然后用白色填充图像背景。

bitmap image = new bitmap(codeweight, codeheight);
graphics g = graphics.fromimage(image);
g.clear(color.white);

④ 画噪音线

在图像上绘制两条随机颜色的噪音线,增加验证码的复杂性。

for (int i = 0; i < 2; i++)
{
    int x1 = rd.next(image.width);
    int x2 = rd.next(image.width);
    int y1 = rd.next(image.height);
    int y2 = rd.next(image.height);
    g.drawline(new pen(color[rd.next(color.length)]), new point(x1, y1), new point(x2, y2));
}

⑤ 画验证码

使用循环逐个绘制验证码字符串中的字符,每个字符使用随机颜色和字体。

for (int i = 0; i < checkcode.length; i++)
{
    color clr = color[rd.next(color.length)];
    font ft = new font(font[rd.next(font.length)], fontsize);
    g.drawstring(checkcode[i].tostring(), ft, new solidbrush(clr), (float)i * 18 + 2, 0);
}

⑥ 画噪音点

在图像上绘制100个随机颜色的噪音点,增加验证码的随机性。 

for (int i = 0; i < 100; i++)
{
    int x = rd.next(image.width);
    int y = rd.next(image.height);
    image.setpixel(x, y, color.fromargb(rd.next()));
}

⑦ 画边框线

在图像周围绘制银色边框线,使验证码更加清晰。

g.drawrectangle(new pen(color.silver), 0, 0, image.width - 1, image.height - 1);

⑧ 将验证码图像保存到内存流

将生成的验证码图像保存到内存流中,准备输出到客户端。

memorystream ms = new memorystream(); image.save(ms, system.drawing.imaging.imageformat.gif);

⑨ 将验证码保存到session中

将生成的验证码字符串保存到session中,以便后续验证。

context.session[constantvalues.vercodesessionname] = checkcode;

⑩ 输出图像到客户端

配置http响应,将验证码图像输出到客户端。

context.response.contenttype = "image/gif";
context.response.clearcontent();
context.response.binarywrite(ms.toarray());

最后,别忘记释放图像和图形资源,防止内存泄漏。

finally { image.dispose(); g.dispose(); }

4、完整后端代码

完整的 vercode.cs 代码如下:

using testmoudle.common;
using system;
using system.drawing;
using system.io;
using system.web;
namespace handlers
{
    public class vercode : ihttphandler, system.web.sessionstate.irequiressessionstate
    {
        public void processrequest(httpcontext context)
        {
            int codeweight = 80;
            int codeheight = 22;
            int fontsize = 16;
            random rd = new random();
            string checkcode = createcode(); //构建验证码字符串
            bitmap image = new bitmap(codeweight, codeheight); //构建画图
            graphics g = graphics.fromimage(image); //构建画布
            g.clear(color.white); //清空背景色
            color[] color = new color[] { color.red, color.black, color.green, color.blue };
            string[] font = new string[] { "宋体", "黑体", "楷体" };
            //画噪音线
            for (int i = 0; i < 2; i++)
            {
                int x1 = rd.next(image.width);
                int x2 = rd.next(image.width);
                int y1 = rd.next(image.height);
                int y2 = rd.next(image.height);
                g.drawline(new pen(color[rd.next(color.length)]), new point(x1, y1), new point(x2, y2));
            }
            //画验证码
            for (int i = 0; i < checkcode.length; i++)
            {
                color clr = color[rd.next(color.length)];
                font ft = new font(font[rd.next(font.length)], fontsize);
                g.drawstring(checkcode[i].tostring(), ft, new solidbrush(clr), (float)i * 18 + 2, 0);
            }
            //画噪音点
            for (int i = 0; i < 100; i++)
            {
                int x = rd.next(image.width);
                int y = rd.next(image.height);
                image.setpixel(x, y, color.fromargb(rd.next()));
            }
            //画边框线
            g.drawrectangle(new pen(color.silver), 0, 0, image.width - 1, image.height - 1);
            memorystream ms = new memorystream();
            try
            {
                image.save(ms, system.drawing.imaging.imageformat.gif);
                context.session[constantvalues.vercodesessionname] = checkcode; //将验证码保存到session中
                context.response.contenttype = "image/gif";
                context.response.clearcontent();
                context.response.binarywrite(ms.toarray());
            }
            finally
            {
                image.dispose();
                g.dispose();
            }
        }
        public bool isreusable
        {
            get
            {
                return false;
            }
        }
    }
}

四、测试效果

我们运行项目,可以看到验证码图像顺利生成了,并且点击可以刷新图片内容。

到此这篇关于asp.net实现图形验证码的文章就介绍到这了,更多相关asp.net图形验证码内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com