ASP. NET graphic verification code control

Source: Internet
Author: User
The graphic verification code is often applied to login or text posting pages on webpages. Because the graphic verification code is difficult to recognize by machines, it can prevent robots. Program Malicious access to webpages. In this article, we will implement a graphical verification code server control, through simple attribute settings can easily apply graphical verification code on the web page.

1. Generate a graphic Verification Code

We will first prepare a page (validatecode. aspx), this page is mainly to draw Verification Code graphics, write it into the memory data stream, and finally use response. binarywrite transmits the graphic output to the client. When the verification code is output, Session ("_ validatecode") is used to record the value of the Verification Code, so that it can be compared with the user's input verification code.

Partial class validatecode
Inherits system. Web. UI. Page

''' <Summary>
''' Generate a signature certificate.
''' </Summary>
''' <Param name = "code"> returns the certificate. </Param>
''' <Param name = "codelength"> the maximum number of characters in the certificate. </Param>
Public Function createvalidatecodeimage (byref code as string, byval codelength as integer ,_
Byval width as integer, byval height as integer, byval fontsize as integer) as bitmap
Dim scode as string = string. Empty
'Invalid color list, used for verification, noise reduction, and noise points
Dim ocolors as color () = {_
Drawing. color. Black, drawing. color. Red, drawing. color. Blue, drawing. color. Green ,_
Drawing. color. Orange, drawing. color. Brown, drawing. color. Brown, drawing. color. darkblue}
'Body list, used for verification purposes
Dim ofontnames as string () = {"Times New Roman", "Ms mincho", "Book antiqua ",_
"Gungsuh", "pmingliu", "impact "}
'Invalid Character Set, removing some confusing characters
Dim ocharacter as char () = {"2" C, "3" C, "4" C, "5" C, "6" C, "8" C ,_
"9" C, "a" C, "B" C, "C" C, "D" C, "E" C ,_
"F" C, "G" C, "H" C, "J" C, "K" C, "L" C ,_
"M" C, "N" C, "P" C, "R" C, "S" C, "T" C ,_
"W" C, "x" C, "Y" c}
Dim ornd as new random ()
Dim obmp as bitmap
Dim ographics as graphics
Dim N1 as integer
Dim opoint1 as drawing. Point
Dim opoint2 as drawing. Point
Dim sfontname as string
Dim ofont as font
Dim ocolor as color

'Generate the signature string
For n1 = 0 to codelength-1
Scode + = ocharacter (ornd. Next (ocharacter. Length ))
Next

Obmp = new Bitmap (width, height)
Ographics = graphics. fromimage (obmp)
Ographics. Clear (drawing. color. White)
Try
For n1 = 0 to 4
'Noise reduction
Opoint1.x = ornd. Next (width)
Opoint1.y = ornd. Next (height)
Opoint2.x = ornd. Next (width)
Opoint2.y = ornd. Next (height)
Ocolor = ocolors (ornd. Next (ocolors. Length ))
Ographics. drawline (new pen (ocolor), opoint1, opoint2)
Next

For n1 = 0 to scode. Length-1
'Invalid Certificate Signature string
Sfontname = ofontnames (ornd. Next (ofontnames. Length ))
Ofont = new font (sfontname, fontsize, fontstyle. italic)
Ocolor = ocolors (ornd. Next (ocolors. Length ))
Ographics. drawstring (scode (N1). tostring (), ofont, new solidbrush (ocolor), csng (N1) * fontsize + 10, csng (8 ))
Next

For I as integer = 0 to 30
'Noise points
Dim X as integer = ornd. Next (obmp. width)
Dim y as integer = ornd. Next (obmp. Height)
Dim CLR as color = ocolors (ornd. Next (ocolors. Length ))
Obmp. setpixel (X, Y, CLR)
Next

Code = scode
Return obmp
Finally
Ographics. Dispose ()
End try
End Function

''' <Summary>
''' Generate a signature certificate.
''' </Summary>
''' <Param name = "memorystream"> records the object stream. </Param>
''' <Param name = "code"> returns the certificate. </Param>
''' <Param name = "codelength"> the maximum number of characters in the certificate. </Param>
Public sub createvalidatecodeimage (byref memorystream as memorystream ,_
Byref code as string, byval codelength as integer ,_
Byval width as integer, byval height as integer, byval fontsize as integer)
Dim obmp as bitmap

Obmp = createvalidatecodeimage (Code, codelength, width, height, fontsize)
Try
Obmp. Save (memorystream, imageformat. PNG)
Finally
Obmp. Dispose ()
End try
End sub

Protected sub page_load (byval sender as object, byval e as system. eventargs) handles me. Load
Dim scode as string = string. Empty

'Clear the outgoing memory of the shard and set the Shard to be unretained.
Response. Buffer = true
Response. expiresabsolute = system. datetime. Now. addmilliseconds (0)
Response. expires = 0
Response. cachecontrol = "no-Cache"
Response. appendheader ("Pragma", "No-Cache ")
'Upload your certificate into the audio stream and export it in "image/PNG" format.
Dim ostream as new memorystream ()
Try
Createvalidatecodeimage (ostream, scode, 4,100, 40, 18)
Me. Session ("_ validatecode") = scode
Response. clearcontent ()
Response. contenttype = "image/PNG"
Response. binarywrite (ostream. toarray ())
Finally
'Metadata Source
Ostream. Dispose ()
End try
End sub
End Class

We set this aspect ~ /Page/validatecode. aspx. When you want to use the authentication certificate of the image, you only need to control the image and set the imageurl to this interface.

<Asp: Image id = "imgvalidatecode" runat = "server" imageurl = "~ /Page/validatecode. aspx "/>

Ii. Verify the ownership of the website

Although we can use the image control to render validatecode. the image of the verification code generated on the ASPX page, but only half of the actions are processed because the "Verification code entered by the user" is not consistent with the "graphic Verification Code, therefore, we will implement a graphical verification code control to deal with all relevant actions.

The preceding example uses the image control to display the verification code. Therefore, the graphic verification code control inherits the image name tbvalidatecode.

<_
Description ("registrant authentication control "),_
Toolboxdata ("<{0}: tbvalidatecode runat = Server> </{0}: tbvalidatecode> ")_
> _
Public class tbvalidatecode
Inherits system. Web. UI. webcontrols. Image

End

Added the validatecodeurl attribute to set the URL on which the graphic verification code is generated.

''' <Summary>
''' Your certificate produces your website address.
''' </Summary>
<_
Description ("graphic interface "),_
Defaultvalue ("")_
> _
Public property validatecodeurl () as string
Get
Return fvalidatecodeurl
End get
Set (byval value as string)
Fvalidatecodeurl = Value
End set
End Property

Override the render method. If the validatecodeurl attribute is not set, the default value is ~ /Page/validatecode. ASPX page. In addition, we add a client instruction code to the ondbclick image, which allows users to re-generate a verification code image with the mouse.

Protected overrides sub render (byval writer as system. Web. UI. htmltextwriter)
Dim Surl as string
Dim sscript as string

Surl = me. validatecodeurl
If string. isnullorempty (Surl) then
Surl = "~ /Page/validatecode. aspx"
End if
If me. borderwidth = unit. Empty then
Me. borderwidth = unit. pixel (1)
End if
If me. alternatetext = string. Empty then
Me. alternatetext = "your signature certificate"
End if
Me. tooltip = "double-click to re-produce the verification code"
Me. imageurl = Surl
If not me. designMode then
Sscript = string. Format ("This. src = '{0 }? Flag = '+ math. Random (); ", me. Page. resolveclienturl (Surl ))
Me. attributes ("ondblclick") = sscript
End if
Me. style (htmltextwriterstyle. cursor) = "Pointer"

Mybase. Render (writer)
End sub

In addition, a validatecode method is added to check whether the entered verification code is correct. Remember to write the value of the verification code into the session ("_ validatecode") when generating the verification code graph, therefore, this method only compares user input values with values in seesion.

''' <Summary>
''' Check whether the entered verification code is correct.
''' </Summary>
''' <Param name = "code"> enter the verification code. </Param>
''' <Returns> returns true for the purchase order, and false for the reverse. </Returns>
Public Function validatecode (byval code as string) as Boolean
If me. Page. Session (sessionkey) is nothing then return false
If sametext (ccstr (Me. Page. Session (sessionkey), Code) then
Return true
Else
Return false
End if
End Function

Iii. Test Procedure

Place a tbvalidatecode control on the page, and add a text box and button for the user to enter the verification code, press the "OK" button, and then enter the Value Comparison action on the server.

<Bee: tbvalidatecode id = "tbvalidatecode1" runat = "server"/>
<Bee: tbtextbox id = "txtcode" runat = "server"> </bee: tbtextbox>
<Bee: tbbutton id = "tbbutton1" runat = "server" text = "Confirm"/>

In the Click Event of the "OK" button, we use the validatecode METHOD OF THE tbvalidatecode control to judge the correctness of the verification code input.

Protected sub tbbutton1_click (byval sender as object, byval e as system. eventargs) handles tbbutton1.click
If tbvalidatecode1.validatecode (txtcode. Text) then
Me. response. Write ("the verification code is entered correctly ")
Else
Me. response. Write ("Incorrect verification code! ")
End if
End sub

When you run the program, the page will generate a Random verification code image.

Enter the correct value and press the "OK" button. The "correct verification code" message is displayed. Because of the relationship we test on the same page, you will find that the verification code graph will be re-generated after PostBack. Generally, the normal practice is to direct the verification to another page after the verification is correct.

When an incorrect value is entered, the system displays "Incorrect verification code !」 .

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.