C#验证码使用
1、C#创建验证码
1.1 创建获取验证码页面(ValidateCode.aspx)
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>获取验证码</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>获取验证码</div>
- </form>
- </body>
- </html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>获取验证码</title>
</head>
<body>
<form id="form1" runat="server">
<div>获取验证码</div>
</form>
</body>
</html>
1.2 编写获取验证码代码(ValidateCode.aspx.cs)
- /// <summary>
- /// 验证码类型(0-字母数字混合,1-数字,2-字母)
- /// </summary>
- private string validateCodeType = "0";
- /// <summary>
- /// 验证码字符个数
- /// </summary>
- private int validateCodeCount = 4;
- /// <summary>
- /// 验证码的字符集,去掉了一些容易混淆的字符
- /// </summary>
- char[] character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
- protected void Page_Load(object sender, EventArgs e)
- {
- //取消缓存
- Response.BufferOutput = true;
- Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
- Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
- Response.AppendHeader("Pragma", "No-Cache");
- //获取设置参数
- if (!string.IsNullOrEmpty(Request.QueryString["validateCodeType"]))
- {
- validateCodeType = Request.QueryString["validateCodeType"];
- }
- if (!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"]))
- {
- int.TryParse(Request.QueryString["validateCodeCount"], out validateCodeCount);
- }
- //生成验证码
- this.CreateCheckCodeImage(GenerateCheckCode());
- }
- private string GenerateCheckCode()
- {
- char code ;
- string checkCode = String.Empty;
- System.Random random = new Random();
- for (int i = 0; i < validateCodeCount; i++)
- {
- code = character[random.Next(character.Length)];
- // 要求全为数字或字母
- if (validateCodeType == "1")
- {
- if ((int)code < 48 || (int)code > 57)
- {
- i--;
- continue;
- }
- }
- else if (validateCodeType == "2")
- {
- if ((int)code < 65 || (int)code > 90)
- {
- i--;
- continue;
- }
- }
- checkCode += code;
- }
- Response.Cookies.Add(new System.Web.HttpCookie("CheckCode", checkCode));
- this.Session["CheckCode"] = 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*15.0+40)), 23);
- System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
- try
- {
- //生成随机生成器
- Random random = new Random();
- //清空图片背景色
- g.Clear(System.Drawing.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 System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
- }
- System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
- System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);
- int cySpace = 16;
- for (int i = 0; i < validateCodeCount; i++)
- {
- g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);
- }
- //画图片的前景噪音点
- for (int i = 0; i < 100; i++)
- {
- int x = random.Next(image.Width);
- int y = random.Next(image.Height);
- image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));
- }
- //画图片的边框线
- g.DrawRectangle(new System.Drawing.Pen(System.Drawing.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);
- Response.ClearContent();
- Response.ContentType = "image/Gif";
- Response.BinaryWrite(ms.ToArray());
- }
- finally
- {
- g.Dispose();
- image.Dispose();
- }
- }
/// <summary>
/// 验证码类型(0-字母数字混合,1-数字,2-字母)
/// </summary>
private string validateCodeType = "0";
/// <summary>
/// 验证码字符个数
/// </summary>
private int validateCodeCount = 4;
/// <summary>
/// 验证码的字符集,去掉了一些容易混淆的字符
/// </summary>
char[] character = { '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' }; protected void Page_Load(object sender, EventArgs e)
{
//取消缓存
Response.BufferOutput = true;
Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.AppendHeader("Pragma", "No-Cache");
//获取设置参数
if (!string.IsNullOrEmpty(Request.QueryString["validateCodeType"]))
{
validateCodeType = Request.QueryString["validateCodeType"];
}
if (!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"]))
{
int.TryParse(Request.QueryString["validateCodeCount"], out validateCodeCount);
}
//生成验证码
this.CreateCheckCodeImage(GenerateCheckCode());
} private string GenerateCheckCode()
{
char code ;
string checkCode = String.Empty;
System.Random random = new Random(); for (int i = 0; i < validateCodeCount; i++)
{
code = character[random.Next(character.Length)]; // 要求全为数字或字母
if (validateCodeType == "1")
{
if ((int)code < 48 || (int)code > 57)
{
i--;
continue;
}
}
else if (validateCodeType == "2")
{
if ((int)code < 65 || (int)code > 90)
{
i--;
continue;
}
}
checkCode += code;
} Response.Cookies.Add(new System.Web.HttpCookie("CheckCode", checkCode));
this.Session["CheckCode"] = 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*15.0+40)), 23);
System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image); try
{
//生成随机生成器
Random random = new Random(); //清空图片背景色
g.Clear(System.Drawing.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 System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
} System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true); int cySpace = 16;
for (int i = 0; i < validateCodeCount; i++)
{
g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);
} //画图片的前景噪音点
for (int i = 0; i < 100; i++)
{
int x = random.Next(image.Width);
int y = random.Next(image.Height); image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));
} //画图片的边框线
g.DrawRectangle(new System.Drawing.Pen(System.Drawing.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);
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
2、验证码的使用
2.1 验证码的前段显示代码
- <img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
<img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
2.2 创建验证码测试页面(ValidateTest.aspx)
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>验证码测试</title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <input runat="server" id="txtValidate" />
- <img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
- <asp:Button runat="server" id="btnVal" Text="提交" onclick="btnVal_Click" />
- </div>
- </form>
- </body>
- </html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>验证码测试</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<input runat="server" id="txtValidate" />
<img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
<asp:Button runat="server" id="btnVal" Text="提交" onclick="btnVal_Click" />
</div>
</form>
</body>
</html>
2.3 编写验证码测试的提交代码(ValidateTest.aspx.cs)
- protected void btnVal_Click(object sender, EventArgs e)
- {
- bool result = false; //验证结果
- string userCode = this.txtValidate.Value; //获取用户输入的验证码
- if (String.IsNullOrEmpty(userCode))
- {
- //请输入验证码
- return;
- }
- string validCode = this.Session["CheckCode"] as String; //获取系统生成的验证码
- if (!string.IsNullOrEmpty(validCode))
- {
- if (userCode.ToLower() == validCode.ToLower())
- {
- //验证成功
- result = true;
- }
- else
- {
- //验证失败
- result = false;
- }
- }
- }
C#验证码使用的更多相关文章
- .net点选验证码实现思路分享
哈哈好久没冒泡了,最进看见点选验证码有点意思,所以想自己写一个. 先上效果图 如果你被这个效果吸引了就请继续看下去. 贴代码前先说点思路: 1.要有一个汉字库,并按字形分类.(我在数据库里是安部首分类 ...
- 【探索】无形验证码 —— PoW 算力验证
先来思考一个问题:如何写一个能消耗对方时间的程序? 消耗时间还不简单,休眠一下就可以了: Sleep(1000) 这确实消耗了时间,但并没有消耗 CPU.如果对方开了变速齿轮,这瞬间就能完成. 不过要 ...
- TODO:Laravel增加验证码
TODO:Laravel增加验证码1. 先聊聊验证码是什么,有什么作用?验证码(CAPTCHA)是"Completely Automated Public Turing test to te ...
- PHP-解析验证码类--学习笔记
1.开始 在 网上看到使用PHP写的ValidateCode生成验证码码类,感觉不错,特拿来分析学习一下. 2.类图 3.验证码类部分代码 3.1 定义变量 //随机因子 private $char ...
- 随手记_C#验证码
前言 最近在网上偶然看见一个验证码,觉得很有意思,于是搜了下,是使用第三方实现的,先看效果: 总体来说效果还是可以的,官方提供的SDK也比较详细,可配置性很高.在这里在简单啰嗦几句使用方式: 使用步骤 ...
- WPF做12306验证码点击效果
一.效果 和12306是一样的,运行一张图上点击多个位置,横线以上和左边框还有有边框位置不允许点击,点击按钮输出坐标集合,也就是12306登陆的时候,需要向后台传递的参数. 二.实现思路 1.获取验证 ...
- 零OCR基础6行代码实现C#验证码识别
这两天因为工作需要,要到某个网站采集信息,一是要模拟登陆,二是要破解验证码,本想用第三方付费打码,但是想想网上免费的代码也挺多的,于是乎准备从网上撸点代码下来,谁知道,撸了好多个都不行,本人以前也没接 ...
- ASP.NET中画图形验证码
context.Response.ContentType = "image/jpeg"; //生成随机的中文验证码 string yzm = "人口手大小多少上中下男女天 ...
- asp.net mvc 验证码
效果图 验证码类 namespace QJW.VerifyCode { //用法: //public FileContentResult CreateValidate() //{ // Validat ...
- ecshop验证码
<?php //仿制ecshop验证码(四位大写字母和数字.背景) //处理码值(四位大写字母和数字组成) //所有的可能的字符集合 $chars = 'ABCDEFGHIJKLMNOPQRST ...
随机推荐
- hadoop资料汇总(网上)
http://blog.csdn.net/fansy1990/article/list/3 全部是hadoop的,挺好. http://stackoverflow.com/ ...
- 浏览器中JavaScript执行原理
本章我们讨论javascript在浏览器中是如果工作的,包括:下载.解析.执行的全过程.javascript的这些讨人嫌的地方我们是知道的: i.需要串行下载 ii.需要解析 iii.需要串行执行 而 ...
- 观察者模式在ng(Angular)中的应用
在这个前端框架满天飞的天下,angular MVVM 的模式确实火了一把,所以最近一直在学习ng,感悟颇多,填坑无数,今天终静下心来打算更新自己久未变动的博客,做一做总结. 1.在ng中的观察者模式: ...
- CentOS LNMP安装phpMyAdmin
假设: 已经配置好LNMP环境,并且Nginx的网页目录在/usr/local/nginx/html 1.下载phpMyAdmin wget https://files.phpmyadmin.net/ ...
- [o] duplicate column name: _id 问题解决
Android下使用SQLite数据库,报错:duplicate column name: _id 数据库文件下有两列数据的名称一样,原因是定义数据类型时有重复,如,我的定义: //复制上一行增加TY ...
- WCF上传、下载、删除文件
关键代码: --上传的stream处理,转为bytep[] private void Parse(Stream stream, Encoding encoding) { this.Success = ...
- iPhone中如何判断当前相机是否可用
UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera; if (![UIImag ...
- [转]Delphi中ShellExecute的妙用
Delphi中ShellExecute的妙用 ShellExecute的功能是运行一个外部程序(或者是打开一个已注册的文件.打开一个目录.打印一个文件等等),并对外部程序有一定的控制. ...
- spring-quartz普通任务与可传参任务
两者区别与作用: 普通任务:总调度(SchedulerFactoryBean)--> 定时调度器(CronTriggerFactoryBean) --> 调度明细自定义执行方法bean(M ...
- Facade 模式
在软件系统开发中经常回会遇到这样的情况,你实现了一些接口(模块),而这些接口(模块)都分布在几个类中(比如 A和 B.C.D) :A中实现了一些接口,B 中实现一些接口(或者 A代表一个独立模块,B. ...