How To Make A Simple Captcha Control In ASP.NET

this is my first tutorial on asp.net by the way i am a beginner , i dont think this is something advanced but hope this is useful . i am gonna teach you how to make a simple captcha control without using any HTTP HANDLERS and you can easily add it to your website . all you need is a aspx page so create one ,, the aspx page will have image/jpg . i am using system.drawing namespace to create dynamic images , system will be generating two random numbers and it will store the results of the two numbers into a session variable .

for instance :

a = 2 + 6 (2 and 6 are two random numbers)

session("Answer") = 8

code for captcha.aspx



Imports System.Drawing

Partial Class Captcha
    Inherits System.Web.UI.Page

 

    Private Sub returnNumer()

        Dim num1 As New Random
        Dim num2 As New Random

        Dim numQ1 As Integer
        Dim numQ2 As Integer
        Dim QString As String


        numQ1 = num1.Next(10, 15)
        numQ2 = num1.Next(17, 31)

 

        QString = numQ1.ToString + " + " + numQ2.ToString + " = "
        Session("answer") = numQ1 + numQ2


        Dim bitmap As New Bitmap(85, 35)
        Dim Grfx As Graphics = Graphics.FromImage(bitmap)
        Dim font As New Font("Arial", 18, FontStyle.Bold, GraphicsUnit.Pixel)
        Dim Rect As New Rectangle(0, 0, 100, 50)

        Grfx.FillRectangle(Brushes.Brown, Rect)
        Grfx.DrawRectangle(Pens.PeachPuff, Rect) ' Border
        Grfx.DrawString(QString, font, Brushes.Azure, 0, 0)

         Response.ContentType = "Image/jpeg"
        bitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg)

        bitmap.Dispose()
        Grfx.Dispose()

     End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Call Me.returnNumer()

    End Sub
End Class


the page_load even generates an image , you can use this within any aspx page for captcha vertification

for instance :

create a textbox(to enter captcha code) and then create a button to verify the captcha code , when clicking the verify button compare the value of the textbox with the session variable session (" ") if the both matches then verification successful .

1 comments:

GENIUS!

Reply

Post a Comment