1、C#创建验证码

1.1 创建获取验证码页面(ValidateCode.aspx)

  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head runat="server">
  3. <title>获取验证码</title>
  4. </head>
  5. <body>
  6. <form id="form1" runat="server">
  7. <div>获取验证码</div>
  8. </form>
  9. </body>
  10. </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)

  1. /// <summary>
  2. /// 验证码类型(0-字母数字混合,1-数字,2-字母)
  3. /// </summary>
  4. private string validateCodeType = "0";
  5. /// <summary>
  6. /// 验证码字符个数
  7. /// </summary>
  8. private int validateCodeCount = 4;
  9. /// <summary>
  10. /// 验证码的字符集,去掉了一些容易混淆的字符
  11. /// </summary>
  12. 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' };
  13. protected void Page_Load(object sender, EventArgs e)
  14. {
  15. //取消缓存
  16. Response.BufferOutput = true;
  17. Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
  18. Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
  19. Response.AppendHeader("Pragma", "No-Cache");
  20. //获取设置参数
  21. if (!string.IsNullOrEmpty(Request.QueryString["validateCodeType"]))
  22. {
  23. validateCodeType = Request.QueryString["validateCodeType"];
  24. }
  25. if (!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"]))
  26. {
  27. int.TryParse(Request.QueryString["validateCodeCount"], out validateCodeCount);
  28. }
  29. //生成验证码
  30. this.CreateCheckCodeImage(GenerateCheckCode());
  31. }
  32. private string GenerateCheckCode()
  33. {
  34. char code ;
  35. string checkCode = String.Empty;
  36. System.Random random = new Random();
  37. for (int i = 0; i < validateCodeCount; i++)
  38. {
  39. code = character[random.Next(character.Length)];
  40. // 要求全为数字或字母
  41. if (validateCodeType == "1")
  42. {
  43. if ((int)code < 48 || (int)code > 57)
  44. {
  45. i--;
  46. continue;
  47. }
  48. }
  49. else if (validateCodeType == "2")
  50. {
  51. if ((int)code < 65 || (int)code > 90)
  52. {
  53. i--;
  54. continue;
  55. }
  56. }
  57. checkCode += code;
  58. }
  59. Response.Cookies.Add(new System.Web.HttpCookie("CheckCode", checkCode));
  60. this.Session["CheckCode"] = checkCode;
  61. return checkCode;
  62. }
  63. private void CreateCheckCodeImage(string checkCode)
  64. {
  65. if (checkCode == null || checkCode.Trim() == String.Empty)
  66. return;
  67. System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length*15.0+40)), 23);
  68. System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
  69. try
  70. {
  71. //生成随机生成器
  72. Random random = new Random();
  73. //清空图片背景色
  74. g.Clear(System.Drawing.Color.White);
  75. //画图片的背景噪音线
  76. for (int i = 0; i < 25; i++)
  77. {
  78. int x1 = random.Next(image.Width);
  79. int x2 = random.Next(image.Width);
  80. int y1 = random.Next(image.Height);
  81. int y2 = random.Next(image.Height);
  82. g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
  83. }
  84. System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
  85. 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);
  86. int cySpace = 16;
  87. for (int i = 0; i < validateCodeCount; i++)
  88. {
  89. g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);
  90. }
  91. //画图片的前景噪音点
  92. for (int i = 0; i < 100; i++)
  93. {
  94. int x = random.Next(image.Width);
  95. int y = random.Next(image.Height);
  96. image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));
  97. }
  98. //画图片的边框线
  99. g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
  100. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  101. image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
  102. Response.ClearContent();
  103. Response.ContentType = "image/Gif";
  104. Response.BinaryWrite(ms.ToArray());
  105. }
  106. finally
  107. {
  108. g.Dispose();
  109. image.Dispose();
  110. }
  111. }
/// <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 验证码的前段显示代码

  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)

  1. <html xmlns="http://www.w3.org/1999/xhtml">
  2. <head runat="server">
  3. <title>验证码测试</title>
  4. </head>
  5. <body>
  6. <form id="form1" runat="server">
  7. <div>
  8. <input runat="server" id="txtValidate" />
  9. <img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" onclick="this.src='/ValidateCode.aspx?ValidateCodeType=1&'+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
  10. <asp:Button runat="server" id="btnVal" Text="提交" onclick="btnVal_Click"  />
  11. </div>
  12. </form>
  13. </body>
  14. </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)

  1. protected void btnVal_Click(object sender, EventArgs e)
  2. {
  3. bool result = false;   //验证结果
  4. string userCode = this.txtValidate.Value; //获取用户输入的验证码
  5. if (String.IsNullOrEmpty(userCode))
  6. {
  7. //请输入验证码
  8. return;
  9. }
  10. string validCode = this.Session["CheckCode"] as String;  //获取系统生成的验证码
  11. if (!string.IsNullOrEmpty(validCode))
  12. {
  13. if (userCode.ToLower() == validCode.ToLower())
  14. {
  15. //验证成功
  16. result = true;
  17. }
  18. else
  19. {
  20. //验证失败
  21. result = false;
  22. }
  23. }
  24. }

C#验证码使用的更多相关文章

  1. .net点选验证码实现思路分享

    哈哈好久没冒泡了,最进看见点选验证码有点意思,所以想自己写一个. 先上效果图 如果你被这个效果吸引了就请继续看下去. 贴代码前先说点思路: 1.要有一个汉字库,并按字形分类.(我在数据库里是安部首分类 ...

  2. 【探索】无形验证码 —— PoW 算力验证

    先来思考一个问题:如何写一个能消耗对方时间的程序? 消耗时间还不简单,休眠一下就可以了: Sleep(1000) 这确实消耗了时间,但并没有消耗 CPU.如果对方开了变速齿轮,这瞬间就能完成. 不过要 ...

  3. TODO:Laravel增加验证码

    TODO:Laravel增加验证码1. 先聊聊验证码是什么,有什么作用?验证码(CAPTCHA)是"Completely Automated Public Turing test to te ...

  4. PHP-解析验证码类--学习笔记

    1.开始 在 网上看到使用PHP写的ValidateCode生成验证码码类,感觉不错,特拿来分析学习一下. 2.类图 3.验证码类部分代码 3.1  定义变量 //随机因子 private $char ...

  5. 随手记_C#验证码

    前言 最近在网上偶然看见一个验证码,觉得很有意思,于是搜了下,是使用第三方实现的,先看效果: 总体来说效果还是可以的,官方提供的SDK也比较详细,可配置性很高.在这里在简单啰嗦几句使用方式: 使用步骤 ...

  6. WPF做12306验证码点击效果

    一.效果 和12306是一样的,运行一张图上点击多个位置,横线以上和左边框还有有边框位置不允许点击,点击按钮输出坐标集合,也就是12306登陆的时候,需要向后台传递的参数. 二.实现思路 1.获取验证 ...

  7. 零OCR基础6行代码实现C#验证码识别

    这两天因为工作需要,要到某个网站采集信息,一是要模拟登陆,二是要破解验证码,本想用第三方付费打码,但是想想网上免费的代码也挺多的,于是乎准备从网上撸点代码下来,谁知道,撸了好多个都不行,本人以前也没接 ...

  8. ASP.NET中画图形验证码

    context.Response.ContentType = "image/jpeg"; //生成随机的中文验证码 string yzm = "人口手大小多少上中下男女天 ...

  9. asp.net mvc 验证码

    效果图 验证码类 namespace QJW.VerifyCode { //用法: //public FileContentResult CreateValidate() //{ // Validat ...

  10. ecshop验证码

    <?php //仿制ecshop验证码(四位大写字母和数字.背景) //处理码值(四位大写字母和数字组成) //所有的可能的字符集合 $chars = 'ABCDEFGHIJKLMNOPQRST ...

随机推荐

  1. Java——(六)Collection之Queue集合

    ------Java培训.Android培训.iOS培训..Net培训.期待与您交流! ------- Queue集合 Queue集合用于模拟队列这种数据结构,队列通常是指“先进先出‘(FIFO)的容 ...

  2. linux下杀死进程(kill)的N种方法 【转】

    转自 http://blog.csdn.net/andy572633/article/details/7211546 首先,用ps查看进程,方法如下: $ ps -ef ……smx       182 ...

  3. Axiom3D学习日记 5.Frame Listeners, and Input Handling

    Frame Listeners In Ogre's C++, we would register a class to receive notification before and after a ...

  4. How to Make LastPass Even More Secure with Google Authenticator

    Google Authenticator LastPass supports Google Authenticator, which is officially available as an app ...

  5. Eclipse中点击小猫提示Tomcat settings should be set in Tomcat Preference Page

    1.window->preference->tomcat->tomcat-version选择自己tomcat版本 tomcat home 选择tomcat安装目录,即bin的上一层 ...

  6. OC - 29.自定义布局实现瀑布流

    概述 瀑布流是电商应用展示商品通常采用的一种方式,如图示例 瀑布流的实现方式,通常有以下几种 通过UITableView实现(不常用) 通过UIScrollView实现(工作量较大) 通过UIColl ...

  7. [LeetCode OJ] Distinct Subsequences

    Given a string S and a string T, count the number of distinct subsequences of T in S. A subsequence ...

  8. javascript——浅谈javascript模版(自定义)

    /** * Created by Administrator on 15-1-19. */ function functionUtil() { } functionUtil = { //某个DOM节点 ...

  9. iOS 视频播放横屏,隐藏状态栏

    MPMoviePlayerViewController *moviePlayerViewController = [[MPMoviePlayerViewController alloc] init]; ...

  10. Extjs4 关于设置form中所有子控件为readOnly属性的解决方案

    之前在网上找了一堆,但那些确实没法用,后来考虑了一下,发现主要是网上提供的假设form中只有一层控件,没有考虑到布局稍微复杂的form情形,此处采用递归的形式实现对form中所有控件(grid及but ...