Generate a verification code on the logon page

Source: Internet
Author: User

It is not difficult to find that each time we log on to a website, there will be a corresponding verification code to verify. In fact, it is not difficult to implement a beautiful verification code. Next we will implement a beautiful Verification Code together.

Generally, the verification code is generated in the same way. The main steps are as follows:

The first step is to randomly generate a number or letter of the system verification code, and write the random numbers or letters into cookies or sessions.

Step 2: Use the random numbers or letters in step 1 to synthesize the image.

It can be seen that the complexity of the verification code is mainly completed in the second step. You can set the Complexity Based on your needs.

Okay. Now you know the basic principles.

Let's take a look.

Step 1: randomly generate numbers or letters

/// <Summary>
/// Random number for generating the verification code
/// </Summary>
/// <Returns> Returns a five-digit random number </returns>
Private string generatecheckcode ()
{
Int number;
Char code;
String checkcode = string. empty;

Random random = new random ();

For (INT I = 0; I <5; I ++) // you can set the number of digits to generate the verification code.
{
Number = random. Next ();

If (Number % 2 = 0)
Code = (char) ('0' + (char) (Number % 10 ));
Else
Code = (char) ('A' + (char) (Number % 26 ));

Checkcode + = code. tostring ();
}

Response. Cookies. Add (New httpcookie ("checkcode", checkcode); // write cookis
Session ["checkcode"] = checkcode; // write to the session. You can select any one of them.
Return checkcode;
}
Step 2: generate an image

/// <Summary>
/// Generate a verification code Image
/// </Summary>
/// <Param name = "checkcode"> </param>
Private void createcheckcodeimage (string checkcode)
{
If (checkcode = NULL | checkcode. Trim () = string. Empty)
Return;

Bitmap image = new Bitmap (INT) math. Ceiling (checkcode. length * 12.5), 22 );
Graphics G = graphics. fromimage (image );

Try
{
// Generate a random Generator
Random random = new random ();

// Clear the background color of the image
G. Clear (color. White );

// Draw the background noise line of the image
For (INT I = 0; I <25; I ++)
{
Int X1 = random. Next (image. width );
Int X2 = random. Next (image. width );
Int Y1 = random. Next (image. Height );
Int y2 = random. Next (image. Height );

G. drawline (new pen (color. Silver), X1, Y1, X2, Y2 );
}

Font font = new system. Drawing. Font ("Arial", 12, (system. Drawing. fontstyle. Bold | system. Drawing. fontstyle. italic ));
Lineargradientbrush brush = new lineargradientbrush (New rectangle (0, 0, image. Width, image. Height), color. Blue, color. darkred, 1.2f, true );
G. drawstring (checkcode, Font, brush, 2, 2 );

// Foreground noise of the image
For (INT I = 0; I <100; I ++)
{
Int x = random. Next (image. width );
Int y = random. Next (image. Height );

Image. setpixel (X, Y, color. fromargb (random. Next ()));
}

// Draw the border line of the image
G. drawrectangle (new pen (color. Silver), 0, 0, image. Width-1, image. Height-1 );

Memorystream MS = new memorystream ();
Image. Save (MS, system. Drawing. imaging. imageformat. GIF );
Response. clearcontent ();
Response. contenttype = "image/GIF ";
Response. binarywrite (Ms. toarray ());
}
Finally
{// Release the object Resource
G. Dispose ();
Image. Dispose ();
}
Complete procedure

Add a checkcode. aspx file to the project in vs2005, and add the following complete code to the checkcode. aspx. CS code file:

Using system;
Using system. Data;
Using system. configuration;
Using system. collections;
Using system. Web;
Using system. Web. Security;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. webcontrols. webparts;
Using system. Web. UI. htmlcontrols;
Using system. drawing;
Using system. IO;
Using system. Drawing. drawing2d;

Public partial class checkcode: system. Web. UI. Page
{
Protected void page_load (Object sender, eventargs E)
{
Createcheckcodeimage (generatecheckcode (); // call the following two methods;
}

/// <Summary>
/// Random number for generating the verification code
/// </Summary>
/// <Returns> Returns a five-digit random number </returns>
Private string generatecheckcode ()
{
Int number;
Char code;
String checkcode = string. empty;

Random random = new random ();

For (INT I = 0; I <5; I ++) // you can set the number of digits to generate the verification code.
{
Number = random. Next ();

If (Number % 2 = 0)
Code = (char) ('0' + (char) (Number % 10 ));
Else
Code = (char) ('A' + (char) (Number % 26 ));

Checkcode + = code. tostring ();
}

Response. Cookies. Add (New httpcookie ("checkcode", checkcode); // write cookis
Session ["checkcode"] = checkcode; // write to the session. You can select any one of them.
Return checkcode;
}

/// <Summary>
/// Generate a verification code Image
/// </Summary>
/// <Param name = "checkcode"> </param>
Private void createcheckcodeimage (string checkcode)
{
If (checkcode = NULL | checkcode. Trim () = string. Empty)
Return;

Bitmap image = new Bitmap (INT) math. Ceiling (checkcode. length * 12.5), 22 );
Graphics G = graphics. fromimage (image );

Try
{
// Generate a random Generator
Random random = new random ();

// Clear the background color of the image
G. Clear (color. White );

// Draw the background noise line of the image
For (INT I = 0; I <25; I ++)
{
Int X1 = random. Next (image. width );
Int X2 = random. Next (image. width );
Int Y1 = random. Next (image. Height );
Int y2 = random. Next (image. Height );

G. drawline (new pen (color. Silver), X1, Y1, X2, Y2 );
}

Font font = new system. Drawing. Font ("Arial", 12, (system. Drawing. fontstyle. Bold | system. Drawing. fontstyle. italic ));
Lineargradientbrush brush = new lineargradientbrush (New rectangle (0, 0, image. Width, image. Height), color. Blue, color. darkred, 1.2f, true );
G. drawstring (checkcode, Font, brush, 2, 2 );

// Foreground noise of the image
For (INT I = 0; I <100; I ++)
{
Int x = random. Next (image. width );
Int y = random. Next (image. Height );

Image. setpixel (X, Y, color. fromargb (random. Next ()));
}

// Draw the border line of the image
G. drawrectangle (new pen (color. Silver), 0, 0, image. Width-1, image. Height-1 );

Memorystream MS = new memorystream ();
Image. Save (MS, system. Drawing. imaging. imageformat. GIF );
Response. clearcontent ();
Response. contenttype = "image/GIF ";
Response. binarywrite (Ms. toarray ());
}
Finally
{// Release the object Resource
G. Dispose ();
Image. Dispose ();
}
}

}

The page for the verification code generated above is ready. Let's call it to see

Add the image control where you need the verification code.

<Asp: Image id = "image1" runat = "server" imageurl = "~ /Checkcode. aspx "/>
The verification code is displayed on the image control!

The display is finished. Of course, we need to determine whether the user input is correct!

As long as we get the user input value, we can compare it with cookis or session.

Request. Cookies ["checkcode"]. Value

Take the session value session ["checkcode"]. tostring () (it is best to first determine whether the session is empty)

If case-insensitive, convert the value entered by the user and the value of cookies or sessions to uppercase or lowercase letters.

Appendix use protected void button#click (Object sender, eventargs E)
{
If (request. Cookies ["checkcode"]. value = textbox1.text. Trim (). tostring ())
{
Response. Write ("cookies are right ");
}
Else
{
Response. Write ("cookies are wrong ");
}

If (session ["checkcode"]! = NULL)
{
If (session ["checkcode"]. tostring (). toupper () = textbox1.text. Trim (). tostring (). toupper ())
// This write can be case insensitive
{
Response. Write ("session is right ");

}
Else
{
Response. Write ("session is wrong ");
}
}
}

 

 

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.