Simple creation of asp.net Verification Code (vb.net + C #)

Source: Internet
Author: User

The general method for creating a verification code on a website is:
1) Use HttpHandler (General handler) to plot Random verification codes, generate random codes, and output them to OutputStream on the page.
2) use Asynchronous methods (such as js) on the page to refresh the verification code of the current page.
[Example]
1) create an "general application processing program ashx" with the following code:
[C #]
Copy codeThe Code is as follows:
Public class ValidationCode: IHttpHandler
{
// Random Generator
Static Random r = new Random (Guid. NewGuid (). GetHashCode ());
// Exclude black and transparent colors because the background color is black
Static PropertyInfo [] colors = (typeof (Brushes ). getProperties (System. reflection. bindingFlags. public | System. reflection. bindingFlags. getProperty | System. reflection. bindingFlags. static )). where (p => p. name! = "Black" & p. Name! = "Transparent"). Select (p => p). ToArray ();
// Exclude the black color because the background color is black
Static PropertyInfo [] linecolors = (typeof (Pens ). getProperties (System. reflection. bindingFlags. public | System. reflection. bindingFlags. getProperty | System. reflection. bindingFlags. static )). where (p => p. name! = "Black"). Select (p => p). ToArray ();
// Obtain the static Brushes Instance Object
Static object colorobj = typeof (Brushes). GetConstructor (BindingFlags. NonPublic, null, Type. EmptyTypes, null );
// Obtain the object of a static Pens instance
Static object penobj = typeof (Pens). GetConstructor (BindingFlags. NonPublic, null, Type. EmptyTypes, null );
// The width of each random character
Const float PERNUMBERWIDTH = 40366f;
// The height of each character
Const float PERNUMBERHEIGHT = 50366f;
Public void ProcessRequest (HttpContext context)
{
// Obtain the number of random numbers to be generated (5 by default)
Int reqNum = 5;
If (context. Request. QueryString ["reqNum"]! = Null)
{
Int. TryParse (context. Request. QueryString ["reqNum"], out reqNum );
}
// How many background images are generated
Bitmap bt = new Bitmap (int) (PERNUMBERWIDTH * reqNum), (int) PERNUMBERHEIGHT );
Graphics g = Graphics. FromImage (bt );
// Generate 4 random numbers (number can be saved to the Session)
String numbers = "";
// Draw a number
For (int I = 1; I <= reqNum; I ++)
{
Numbers + = r. Next (0, 9). ToString ();
Var color = (PropertyInfo) colors. GetValue (r. Next (0, colors. Length ));
Context. Response. Write (color. Name + "<br/> ");
Brush randomcolor = (Brush) color. GetValue (colorobj, null );
G. DrawString (numbers [I-1]. ToString (), new Font ("", PERNUMBERWIDTH), randomcolor, new PointF (I-1) * PERNUMBERWIDTH, 0f ));
}
// Draw random lines
Int linenum = r. Next (10, 21 );
For (int I = 1; I <= linenum; I ++)
{
Var linecolor = (PropertyInfo) linecolors. GetValue (r. Next (0, colors. Length ));
Pen randomcolor = (Pen) linecolor. GetValue (penobj, null );
G. drawLine (randomcolor, new PointF (float) (r. nextDouble () * PERNUMBERWIDTH * reqNum), (float) (r. nextDouble () * PERNUMBERHEIGHT), new PointF (float) (r. nextDouble () * PERNUMBERWIDTH * reqNum), (float) (r. nextDouble () * PERNUMBERHEIGHT )));
}
G. Dispose ();
Context. Response. Clear ();
Context. Response. ContentType = "image/jpeg ";
Bt. Save (context. Response. OutputStream, ImageFormat. Jpeg );
Bt. Dispose ();
Context. Response. End ();
}
Public bool IsReusable
{
Get
{
Return false;
}
}
}

[VB. NET]
Copy codeThe Code is as follows:
Public Class ValidationCode
Implements IHttpHandler
'Random Generator
Shared r As New Random (Guid. NewGuid (). GetHashCode ())
'Exclude black and transparent colors because the background color is black
Shared colors As PropertyInfo () = (GetType (Brushes ). getProperties (System. reflection. bindingFlags. [Public] Or System. reflection. bindingFlags. getProperty Or System. reflection. bindingFlags. [Static]). where (Function (p) p. name <> "Black" AndAlso p. name <> "Transparent "). [Select] (Function (p ). toArray ()
'Exclude the black color because the background color is black.
Shared linecolors As PropertyInfo () = (GetType (Pens ). getProperties (System. reflection. bindingFlags. [Public] Or System. reflection. bindingFlags. getProperty Or System. reflection. bindingFlags. [Static]). where (Function (p) p. name <> "Black "). [Select] (Function (p ). toArray ()
'Get static Brushes instance objects
Shared colorobj As Object = GetType (Brushes). GetConstructor (BindingFlags. NonPublic, Nothing, Type. EmptyTypes, Nothing)
'Get static Pens Instance Object
Shared penobj As Object = GetType (Pens). GetConstructor (BindingFlags. NonPublic, Nothing, Type. EmptyTypes, Nothing)
'The width of each random character
Const PERNUMBERWIDTH As Single = 40F
'The height of each character
Const PERNUMBERHEIGHT As Single = 50F
Public Sub ProcessRequest (context As HttpContext)
'The number of random numbers to be generated (5 by default)
Dim reqNum As Integer = 5
If context. Request. QueryString ("reqNum") IsNot Nothing Then
Integer. TryParse (context. Request. QueryString ("reqNum"), reqNum)
End If
'How many background images are generated?
Dim bt As New Bitmap (CInt (Math. Truncate (PERNUMBERWIDTH * reqNum), CInt (Math. Truncate (PERNUMBERHEIGHT )))
Dim g As Graphics = Graphics. FromImage (bt)
'Generate four random numbers (number can be saved to the Session)
Dim numbers As String = ""
'Draw a number
For I As Integer = 1 To reqNum
Numbers + = r. [Next] (0, 9). ToString ()
Dim color = DirectCast (colors. GetValue (r. [Next] (0, colors. Length), PropertyInfo)
Context. Response. Write (Convert. ToString (color. Name) & "<br/> ")
Dim randomcolor As Brush = DirectCast (color. GetValue (colorobj, Nothing), Brush)
G. drawString (numbers (I-1 ). toString (), New Font ("", PERNUMBERWIDTH), randomcolor, New PointF (I-1) * PERNUMBERWIDTH, 0F ))
Next
'Draw random lines
Dim linenum As Integer = r. [Next] (10, 21)
For I As Integer = 1 To linenum
Dim linecolor = DirectCast (linecolors. GetValue (r. [Next] (0, colors. Length), PropertyInfo)
Dim randomcolor As Pen = DirectCast (linecolor. GetValue (penobj, Nothing), Pen)
G. drawLine (randomcolor, New PointF (CSng (r. nextDouble () * PERNUMBERWIDTH * reqNum), CSng (r. nextDouble () * PERNUMBERHEIGHT), New PointF (CSng (r. nextDouble () * PERNUMBERWIDTH * reqNum), CSng (r. nextDouble () * PERNUMBERHEIGHT )))
Next
G. Dispose ()
Context. Response. Clear ()
Context. Response. ContentType = "image/jpeg"
Bt. Save (context. Response. OutputStream, ImageFormat. Jpeg)
Bt. Dispose ()
Context. Response. [End] ()
End Sub
Public ReadOnly Property IsReusable () As Boolean
Get
Return False
End Get
End Property
End Class

Note:
1) some specific attributes such as Brushes are public and all color attribute lists need to be obtained through reflection. Therefore, static variables are used so that they do not have to be initialized every time, saving both memory and time.
2) Brushes avoids black and transparent colors (in this example, the background color is black), and Pens only needs to avoid black. For the Brushes color, see: http://msdn.microsoft.com/zh-cn/library/system.windows.media.brush (v = vs.95). aspx
3) The Bitmap class is used for plotting. Generally, it is a blank black background. Generally used in combination with the Image class + Graphics canvas for painting.
4) The Save method of BitMap has several overloaded versions, one of which can specify the output stream and set the image format. This function is used in this example.
[Application]

Code in Html (Verification Code part, partial ):
Copy codeThe Code is as follows:
<H1>
Verification Code
</H1>
<Script>
Function ChangeSD (){
Document. getElementById ("imgSD"). src = "";
Document. getElementById ("imgSD"). src = "/ValidationCode. ashx? ReqNum = 10 ";
};
</Script>

<Input type = "button" value = "Change Validation Key" onclick = "ChangeSD ()"/>

Note: The reason why I use js to set the img src twice is that duplicate paths do not cause requests.

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.