Truemag

  • Categories
    • Tips And Tricks
    • Internet
    • PHP
    • Javascript
    • CSharp
    • SQL Server
    • Linux
  • Lastest Videos
  • Our Demos
  • About
  • Contact
  • Home
  • Write With Us
  • Job Request
Home CSharp Create Simple Math (Mathematical) Captcha With ASP.NET C#

Create Simple Math (Mathematical) Captcha With ASP.NET C#

Following ASP.NET (C#) code below will create, display and verify Math Captcha (Mathematical Captcha) for you be able to rapidly integrate into aspx page functions such as login, registration, comment, forgot password, etc to prevent SPAM.

We’re creating 2 files: one for creating the Math Captcha image and one for display and verifying the Math Captcha.

Create Math Captcha With ASP.NET C#

1. Create The Math Captcha Image

Create an aspx file named for example simple-math-captcha.aspx and code behind file named simple-math-captcha.aspx.cs – Visual C# with content as below:

+ simple-math-captcha.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="simple-math-captcha.aspx.cs" Inherits="simple_math_captcha" %>

+ simple-math-captcha.aspx.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Text;
using System.IO;
 
public partial class simple_math_captcha : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.AddHeader("p3p", "CP=\"CAO PSA OUR\"");
 
        Color myColor = System.Drawing.Color.Red;
 
        Bitmap objBMP = new System.Drawing.Bitmap(80, 30);
        Graphics objGraphics = System.Drawing.Graphics.FromImage(objBMP);
        objGraphics.Clear(Color.Transparent);
 
        Font objFont = new Font("Arial", 12, FontStyle.Regular);
 
        string randomStr = "";
 
        Random r = new Random();
 
        int a = r.Next(1, 99);
        int b = r.Next(1, 99);
 
        int c = a + b;
 
        randomStr = a.ToString() + " + " + b.ToString() + " = ";
 
        Session["LoyatyMathCaptcha"] = c.ToString();
 
        SolidBrush myBrush = new SolidBrush(myColor);
 
        objGraphics.DrawString(randomStr, objFont, myBrush, 3, 3);
 
        Response.ContentType = "image/png";
 
        System.IO.MemoryStream mem = new MemoryStream();
 
        objBMP.Save(mem, ImageFormat.Png);
        mem.WriteTo(Response.OutputStream);
 
        objFont.Dispose();
        objGraphics.Dispose();
        objBMP.Dispose();
    }
}

Notes:

  • Set allow session on IE load by Iframe/ Frame, line 16
  • Math Captcha image text color: Red, line 18
  • Math Captcha image size is 80×30, line 20
  • Text font for the Math Captcha image: Arial and size: 12, line 24
  • Create the math, ex: A + B = C, from line 26 to 35
  • Create a Session named for example “LoyatyMathCaptcha” to store the right result, will use to verify the math captcha, line 37
  • Set the content type: PNG and return the image, line 43

2. Display and verify the Math Captcha Image

Create an aspx file named for example simple-math-captcha-demo.aspx and code behind file named simple-math-captcha-demo.aspx.cs – Visual C# with content as below:

+ simple-math-captcha-demo.aspx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="simple-math-captcha-demo.aspx.cs" Inherits="simple_math_captcha_demo" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <table>
        <tr>
            <td colspan="2">Enter Captcha (with number)</td>
        </tr>
        <tr>
            <td colspan="2"><asp:Label ForeColor="Red" runat="server" ID="lblMessage"></asp:Label></td>
        </tr>
        <tr>
            <td><img src="simple-math-captcha.aspx" /></td>
            <td><asp:TextBox runat="server" ID="txtCaptcha"></asp:TextBox></td>
        </tr>
        <tr><td colspan="2"><asp:Button runat="server" ID="btnSubmit" Text="Submit" onclick="btnSubmit_Click" /></td></tr>
    </table>
    </form>
</body>
</html>

Note: in order to increase the user experience, we should implement JQuery allows only numbers in the textbox.

+ simple-math-captcha-demo.aspx.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class simple_math_captcha_demo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string captcha = txtCaptcha.Text;
 
        if (captcha == Session["LoyatyMathCaptcha"].ToString())
        {
            lblMessage.Text = "Correct!";
        }
        else
        {
            lblMessage.Text = "InCorrect!";
        }
    }
}

If we need to implement a more complicate/securier Captcha, consider to implement Google Captcha also with ASP.NET (C#).

Nov 5, 2014 Hoan Huynh

Source Code Demo page

Google Chrome Runs Very Slow When Selecting Text Or Typing Text MySQL Convert Varchar To Int
You Might Also Like:
  • Implement Google Captcha (reCAPTCHA) With ASP.NET
  • Implement Google Captcha (reCAPTCHA) With PHP
  • When we need to implement CAPTCHA
  • Asp.net Gridview Simple Example
  • Create Free SSL Certificate For Testing On Windows Server 2003 IIS 6
  • Javascript generate a random number using Math.random
  • Create Auto Refresh Page Or Redirect After A Given Seconds
  • Google Map Supported Type And Simple Example
  • C# Read Json From URL And Parse/Deserialize Json
  • Create CrmService with Domain, Username And Password
Hoan Huynh

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com

Link4 years ago CSharpCAPTCHA, ContentType, FontStyle, ImageFormat, Math Captcha, MemoryStream, OutputStream1,062
0
GooglePlus
0
Facebook
0
Twitter
0
Digg
0
Delicious
0
Stumbleupon
0
Linkedin
0
Pinterest
Most Viewed
PHP Download Image Or File From URL
16,466 views
Notepad Plus Plus Compare Plugin
How To Install Compare Text Plugin In Notepad Plus Plus
12,284 views
Microsoft SQL Server 2008 Attach Remove Log
Delete, Shrink, Eliminate Transaction Log .LDF File
11,623 views
JQuery Allow only numeric characters or only alphabet characters in textbox
9,611 views
PHP Call Web Service WSDL Example
6,451 views
4 Rapid Development is a central page that is targeted at newbie and professional programmers, database administrators, system admin, web masters and bloggers.
Recent Posts
  • Magento Fatal error: Unsupported operand types
  • Ionic bower the name contains uppercase letters
  • PHP Magento Get Manufacturer Name And ID From Magento Product ID
  • Know Simple Hacks To Systematize Media Library in WordPress
  • A handy guideline on adding custom menu item in WordPress admin
Categories
  • CSharp (45)
  • Facebook Graph API (19)
  • Google API (7)
  • Internet (87)
  • iPhone XCode (8)
  • Javascript (35)
  • Linux (26)
  • MySQL (16)
  • PHP (84)
  • Problem Issue Error (29)
  • Resources (32)
  • SQL Server (25)
  • Timeline (5)
  • Tips And Tricks (140)
EMAIL SUBSCRIPTION

Sign up for our newsletter to receive the latest news and event postings.

Recommended
  • CDN
  • Hosting
  • Premium Themes
  • VPS
2014 © 4 Rapid Development