Before proceeding with the topic first we must understand "What is a Captcha code?" and "Why do we use them?". Most web sites have a Captcha validation in their sites.

What is the Captcha code?

A Captcha code is simply a combination of some characters and numbers like "Alk13" or "aTu2eP" etc.

Why do we use them?

We use them for validating that the client browser window really has a human typing into it.

Ok, let's get to the topic i.e. creating your own Captcha code in ASP.Net.

Step 1

Go to Visual Studio and create a new project (web site or web application) say "CaptchCode".

Step 2

Now add a new page into your application say "ShowCaptcha.aspx" and add this code into the source for the page:

  1. <div>
  2. <table>
  3. <tr>
  4. <td>
  5. <asp:Image ID="imgCaptcha" runat="server" ImageUrl="~/CreateCaptcha.aspx?New=1"/>
  6. </td>
  7. </tr>
  8. <tr>
  9. <td>
  10. <asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox>
  11. </td>
  12. </tr>
  13. <tr>
  14. <td>
  15. <asp:Label ID="lblMessage" runat="server"></asp:Label>
  16. </td>
  17. </tr>
  18. <tr>
  19. <td>
  20. <asp:Button ID="btnCaptcha" runat="server" Text="Validate Cpatcha Code" onclick="btnCaptcha_Click" />
  21. </td>
  22. </tr>
  23. </table>
  24. </div>

Note: Here I am given the ImageUrl="~/CreateCaptcha.aspx?New=1" of the image control. In CreateCaptcha.aspx we will write the code for creating the Captcha code.

Step 3

Now add a new page into your application "CreateCaptcha.aspx" and create the following methods in its .cs file:

  1. /// <summary>
  2.  
  3. /// method for create captcha image
  4.  
  5. /// </summary>
  6.  
  7. private void CreateCaptchaImage()
  8.  
  9. {
  10.  
  11. code = GetRandomText();
  12.  
  13. Bitmap bitmap = new Bitmap(, , System.Drawing.Imaging.PixelFormat.Format32bppArgb);
  14.  
  15. Graphics g = Graphics.FromImage(bitmap);
  16.  
  17. Pen pen = new Pen(Color.Yellow);
  18.  
  19. Rectangle rect = new Rectangle(, , , );
  20.  
  21. SolidBrush blue = new SolidBrush(Color.CornflowerBlue);
  22.  
  23. SolidBrush black = new SolidBrush(Color.Black);
  24.  
  25. int counter = ;
  26.  
  27. g.DrawRectangle(pen, rect);
  28.  
  29. g.FillRectangle(blue, rect);
  30.  
  31. for (int i = ; i < code.Length; i++)
  32.  
  33. {
  34.  
  35. g.DrawString(code[i].ToString(), new Font("Tahoma", + rand.Next(, ), FontStyle.Italic), black, newPointF( + counter, ));
  36.  
  37. counter += ;
  38.  
  39. }
  40.  
  41. DrawRandomLines(g);
  42.  
  43. bitmap.Save(Response.OutputStream, ImageFormat.Gif);
  44.  
  45. g.Dispose();
  46.  
  47. bitmap.Dispose();
  48.  
  49. }
  50.  
  51. /// <summary>
  52.  
  53. /// Method for drawing lines
  54.  
  55. /// </summary>
  56.  
  57. /// <param name="g"></param>
  58.  
  59. private void DrawRandomLines(Graphics g)
  60.  
  61. {
  62.  
  63. SolidBrush yellow = new SolidBrush(Color.Yellow);
  64.  
  65. for (int i = ; i < ; i++)
  66.  
  67. {g.DrawLines(new Pen(yellow, ), GetRandomPoints());}
  68.  
  69. }
  70.  
  71. /// <summary>
  72.  
  73. /// method for gettting random point position
  74.  
  75. /// </summary>
  76.  
  77. /// <returns></returns>
  78.  
  79. private Point[] GetRandomPoints()
  80.  
  81. {
  82.  
  83. Point[] points = { new Point(rand.Next(, ), rand.Next(, )), new Point(rand.Next(, ), rand.Next(, )) };
  84.  
  85. return points;
  86.  
  87. }
  88.  
  89. /// <summary>
  90.  
  91. /// Method for generating random text of 5 cahrecters as captcha code
  92.  
  93. /// </summary>
  94.  
  95. /// <returns></returns>
  96.  
  97. private string GetRandomText()
  98.  
  99. {
  100.  
  101. StringBuilder randomText = new StringBuilder();
  102.  
  103. string alphabets = "012345679ACEFGHKLMNPRSWXZabcdefghijkhlmnopqrstuvwxyz";
  104.  
  105. Random r = new Random();
  106.  
  107. for (int j = ; j <= ; j++)
  108.  
  109. {randomText.Append(alphabets[r.Next(alphabets.Length)]);}
  110.  
  111. Session["CaptchaCode"] = randomText.ToString();
  112.  
  113. return Session["CaptchaCode"] as String;
  114.  
  115. }

Step 4 

To validate the Captcha code in the "ShowCaptcha.aspx.cs" page:

  1. protected void btnCaptcha_Click(object sender, EventArgs e)
  2.  
  3. {
  4.  
  5. //imgCaptcha.ImageUrl = "~/CreateCaptcha.aspx?New=0";
  6.  
  7. if (Session["CaptchaCode"] != null && txtCaptcha.Text == Session["CaptchaCode"].ToString())
  8.  
  9. {
  10.  
  11. lblMessage.ForeColor = Color.Green;
  12.  
  13. lblMessage.Text = "Captcha code validated successfully!!";
  14.  
  15. }
  16.  
  17. else
  18.  
  19. {
  20.  
  21. lblMessage.ForeColor = Color.Red;
  22.  
  23. lblMessage.Text = "Captcha code is wrong!!";
  24.  
  25. }
  26.  
  27. }

I hope this article will be helpful for you.

Happy Coding!!

附代码:下载

asp.net 验证码的更多相关文章

  1. ASP.net 验证码(C#) MVC

    ASP.net 验证码(C#) MVC http://blog.163.com/xu_shuhao/blog/static/5257748720101022697309/ 网站添加验证码,主要为防止机 ...

  2. MVC的验证(模型注解和非侵入式脚本的结合使用) .Net中初探Redis .net通过代码发送邮件 Log4net (Log for .net) 使用GDI技术创建ASP.NET验证码 Razor模板引擎 (RazorEngine) .Net程序员应该掌握的正则表达式

    MVC的验证(模型注解和非侵入式脚本的结合使用)   @HtmlHrlper方式创建的标签,会自动生成一些属性,其中一些属性就是关于验证 如图示例: 模型注解 通过模型注解后,MVC的验证,包括前台客 ...

  3. Asp.Net验证码2

    using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System. ...

  4. 关于 ASP.NET 验证码

    Session["CheckCode"] 这个..不懂神马意思.. .创建一个用户控件 用户名:TextBox 密码: TextBox 验证码:TextBox 验证码图片 < ...

  5. ASP.NET 验证码 不同浏览器 不刷新问题

    具体为什么不刷新是缓存机制不同,验证码图片的src或ImageUrl的获取是来自一个文件,由于连接地址没变所以不同内核浏览器有的会认为源没有变,解决办法就是在连接后面加上一个随机参数如可以用JS的Ma ...

  6. asp.net验证码及怎么获取里面的数值(整合)

    一.ASP.Net的验证码的作用 对于一个预防攻击的web表单来讲,验证码通常是一个常见的措施.因为如果对于一些public区域的页面内容来讲,譬如一个登录表单,如果没有必要的安全措施,很可能遭到模拟 ...

  7. ASP.NET——验证码的制作

            我们在登陆站点,发表博客或者提交评论的时候,常常会遇到填写验证码这一项,当时感觉挺奇妙的样子,最终在牛腩新闻公布系统里接触到了,在这里小小的总结下.         用到的东东有三个: ...

  8. asp.net 验证码技术

    网站验证码是一种很常用的技术.下面我介绍下技术上是如何实现的. 验证码是一张图片.我们需要在前台代码中写一段<img>,src指向一张页面(ValidateImage.aspx). < ...

  9. asp.net验证码的编写

    很多时候我们在登录什么网站的时候,除了需要什么用户名和密码之外,有的还需要验证码那么在asp.net中这个验证码如何编写和设计,今天我就来给大家说一下: 首先创建一个页面名字随便起一个,我们这里叫做C ...

  10. asp.net验证码

    asp.net 生成验证码问题 .添加一个.ashx文件 <%@ WebHandler Language="C#" class="CheckCode" % ...

随机推荐

  1. Navi.Soft31.代码生成器(含下载地址)

    1系统简介 1.1功能简述 在Net软件开发过程中,大部分时间都是在编写代码,并且都是重复和冗杂的代码.比如:要实现在数据库中10个表的增删改查功能,大部分代码都是相同的,只需修改10%的代码量.此时 ...

  2. android适配pad和部分手机底部虚拟按键+沉浸式状态栏

    在使用沉浸式状态栏设置界面全屏时发现pad和部分手机(华为和魅族系统自带)屏幕底部会带有虚拟按键,遮挡住界面本身的一部分. 为了设置隐藏,在网上找了一些方法,设置Activity主题再在布局加fits ...

  3. MATLAB——textscan

    %读取带变量名的数据集的程序,寇文红2007年5月24日于畅春园. %这是一个读取数据集的程序,目的是把如下带变量名的数据矩阵读进MATLAB.% <DTYYYYMMDD>,<TIM ...

  4. I/O多路复用和Socket

    由于IO操作涉及到系统调用,涉及到用户空间和内核空间的切换,所以理解系统的IO模型,对于需要进入到系统调用层面进行编程来说是很重要的. 阻塞IO和非阻塞IO 从程序编写的角度来看,I/O就是调用一个或 ...

  5. Oracle 11g 数据库 shutdown 后立即执行 startup mount 报错的解决办法

    最新文章:Virson's Blog 今天在配置Goldengate时Capture进程提示未开启归档日志,然后立即用sys用户登录orcl数据库,然后执行了“shutdown immediate”命 ...

  6. vnc server on Ubuntu

    Virtual Network Computing(VNC)是进行远程桌面控制的一个软件.客户端的键盘输入和鼠标操作通过网络传输到远程服务器,控制服务器的操作   (只有背景,没有菜单栏问题没有解决) ...

  7. 1、Maven安装教程详解

    一.准备工作  1.确定电脑上已经成功安装jdk7.0以上版本                 2.win10操作系统                 3.maven安装包            下载 ...

  8. JAVA获取系统相关信息

    Version:0.9 StartHTML:-1 EndHTML:-1 StartFragment:00000099 EndFragment:00003596 获取JRE系统相关参数 java 通过S ...

  9. Android wifi powersave

    使用高通平台的查看power save的功能. 一般是控制WCNSS_qcom_cfg.ini文件的两个参数gEnableBmps,gEnableImps. BMPS: Beacon mode pow ...

  10. Java数组扩展

    Java中,数组初始化后如何扩展数组? 示例 以下示例显示如何在创建新并初始化数组后扩展数组. package com.yiibai; public class ExtendingArray { pu ...