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:

<div>
<table>
<tr>
<td>
<asp:Image ID="imgCaptcha" runat="server" ImageUrl="~/CreateCaptcha.aspx?New=1"/>
</td>
</tr>
<tr>
<td>
<asp:TextBox ID="txtCaptcha" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnCaptcha" runat="server" Text="Validate Cpatcha Code" onclick="btnCaptcha_Click" />
</td>
</tr>
</table>
</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:

/// <summary>

/// method for create captcha image

/// </summary>

 private void CreateCaptchaImage()

{ 

 code = GetRandomText();

 Bitmap bitmap = new Bitmap(, , System.Drawing.Imaging.PixelFormat.Format32bppArgb);

 Graphics g = Graphics.FromImage(bitmap);

 Pen pen = new Pen(Color.Yellow);

 Rectangle rect = new Rectangle(, , , );

 SolidBrush blue = new SolidBrush(Color.CornflowerBlue);

 SolidBrush black = new SolidBrush(Color.Black);

 int counter = ;

 g.DrawRectangle(pen, rect);

 g.FillRectangle(blue, rect);

 for (int i = ; i < code.Length; i++)

 {

    g.DrawString(code[i].ToString(), new Font("Tahoma",  + rand.Next(, ), FontStyle.Italic), black, newPointF( + counter, ));

   counter += ;

 }

 DrawRandomLines(g);          

 bitmap.Save(Response.OutputStream, ImageFormat.Gif);

 g.Dispose();

 bitmap.Dispose();

}

/// <summary>

/// Method for drawing lines

/// </summary>

/// <param name="g"></param>

private void DrawRandomLines(Graphics g)

{

   SolidBrush yellow = new SolidBrush(Color.Yellow);

   for (int i = ; i < ; i++)

   {g.DrawLines(new Pen(yellow, ), GetRandomPoints());}

}

/// <summary>

/// method for gettting random point position

/// </summary>

/// <returns></returns>

private Point[] GetRandomPoints()

{

  Point[] points = { new Point(rand.Next(, ), rand.Next(, )), new    Point(rand.Next(, ), rand.Next(, )) };

  return points;

}

/// <summary>

/// Method for generating random text of 5 cahrecters as captcha code

/// </summary>

/// <returns></returns>

private string GetRandomText()

{

  StringBuilder randomText = new StringBuilder();          

  string alphabets = "012345679ACEFGHKLMNPRSWXZabcdefghijkhlmnopqrstuvwxyz";

  Random r = new Random();

  for (int j = ; j <= ; j++)

  {randomText.Append(alphabets[r.Next(alphabets.Length)]);}

    Session["CaptchaCode"] = randomText.ToString();

     return Session["CaptchaCode"] as String;

  }

Step 4 

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

protected void btnCaptcha_Click(object sender, EventArgs e)

{

   //imgCaptcha.ImageUrl = "~/CreateCaptcha.aspx?New=0";

  if (Session["CaptchaCode"] != null && txtCaptcha.Text == Session["CaptchaCode"].ToString())

  {

     lblMessage.ForeColor = Color.Green;

     lblMessage.Text = "Captcha code validated successfully!!";

  }

  else

  {

   lblMessage.ForeColor = Color.Red;

   lblMessage.Text = "Captcha code is wrong!!";

  }

}

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. DataWindow.Net组件示例(全部开源)

    1概述 1.1功能简介 Sybase公司的PowerBuilder开发工具,在以前VS工具没有成事以前,是相当风光的.微软都要与其合作,学习它Db方面的技术,才成就了SQLServer数据库.PB开发 ...

  2. Web服务端开发需要考虑的问题(续)

    方案汇总API设计应用架构代码库管理工具链工作计划目标预期关键过程service-driver接口定义及实现web样例 方案汇总 API设计 基于https. 只提供纯数据. 基于一开始提出的rest ...

  3. C#/.NET 学习之路——从入门到放弃

    原文链接地址:http://blog.liuhaoyang.me/dotnet/2016/11/25/csharp-books/ 向架构师大步迈进的书单 C# 入门 <C# 本质论> &l ...

  4. 解决Android 7.0 App内切换语言不生效的问题

    Android7.0及以前版本,Configuration中的语言相当于是App的全局设置: public static void changeAppLanguage(Context context, ...

  5. 你应该知道的CSS2.0中最常用的18条技巧

    一.使用css缩写 使用缩写可以帮助减少你CSS文件的大小,更加容易阅读.  具体内容请浏览:CSS常用缩写语法 二.明确定义单位,除非值为0. 忘记定义尺寸的单位是CSS新手普遍的错误.在HTML中 ...

  6. thinkphp5的Redis缓存配置

    thinkphp采用cache类提供缓存功能支持,采用驱动方式,在使用缓存之前需要进行初始化操作.支持的缓存类型包括file.memcache.wincache.sqlite.redis和xcache ...

  7. 大型网站的SEO引爆点

    网站越大,SEO服务做起来就轻松,因为大型网站都有很好的执行团队,你只需要找准他们网站的SEO爆破点,就能够迅速获得非常理想的SEO效果.本文将结合我最近两年的几个经典案例:腾讯拍拍.金山爱词霸.中青 ...

  8. Spring JDBC SqlQuery类示例

    org.springframework.jdbc.object.SqlQuery类提供了表示SQL查询的可重用操作对象. 使用到的 Student 表的结构如下 - CREATE TABLE Stud ...

  9. java EE 环境配置(JDK + Tomcat + Eclipse for java EE)

    这学期的课程多数都是java语言的,像Java Web程序设计,java课程设计案例,所以趁周末先把软件,环境配置好. 下载JDK 先给上下载链接:http://www.oracle.com/tech ...

  10. Java虚拟机性能管理神器 - VisualVM(1) 简介 - JVM轻量级监控分析神器

    目录(?)[-] 一VisualVM是什么 二如何获取VisualVM 三获取那个版本 四VisualVM能做什么 显示JAVA应用程序配置和运行时环境 显示本地和远程JAVA应用程序运行状态 监控应 ...