. NET generate random Verification Code

Source: Internet
Author: User
Create a new Web form named "RandomImage. aspx" to output an image containing four random verification codes. The characters are numbers or uppercase letters. It uses a basic knowledge: numbers 0 ~ 9 The corresponding ASCII code is 48 ~ 57, Letter ~ The ASCII code corresponding to Z is 65 ~ 90. When a Random verification code is generated, the program saves the verification code through Cookies for comparison when submitting the form.

The following is the RandomImage. aspx code:
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; // header file of the Graphics class

Public partial class RandomImage: System. Web. UI. Page
{
Protected void Page_Load (object sender, EventArgs e)
{
This. CreateCheckCodeImage (GenerateCheckCode ());
}
# Code generated by region web Form Designer
Override protected void OnInit (EventArgs e)
{
//
// CODEGEN: This call is required by the asp. NET web form designer.
//
InitializeComponent ();
Base. OnInit (e );
}

/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
Private void InitializeComponent ()
{
This. Load + = new System. EventHandler (this. Page_Load );
}
# Endregion

Private string GenerateCheckCode ()
{
Int number;
String checkCode = String. Empty; // string for storing random Codes

System. Random random = new Random ();

For (int I = 0; I <4; I ++) // generates a four-digit Verification Code
{
Number = random. Next ();
Number = number % 36;
If (number <10)
{
Number + = 48; // The number 0-9 is encoded in 48-57
}
Else
{
Number + = 55; // The letter A-Z is encoded in 65-90
}

CheckCode + = (char) number). ToString ();
}

Response. Cookies. Add (new HttpCookie ("CheckCode", checkCode); // store random codes in Cookies

Return checkCode;
}

Private void CreateCheckCodeImage (string checkCode)
{
If (checkCode = null | checkCode. Trim () = String. Empty)
Return;

System. Drawing. Bitmap image = new System. Drawing. Bitmap (
(Int) Math. Ceiling (decimal) (checkCode. Length * 15), 20 );
// Create a Graphics object
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 );

// 10 background noise lines
For (int I = 0; I <10; I ++)
{
// Noise line start coordinate (x1, y1), end coordinate (x2, y2)
Int x1 = random. Next (image. Width );
Int x2 = random. Next (image. Width );
Int y1 = random. Next (image. Height );
Int y2 = random. Next (image. Height );
// Draw the noise line with a silver line
G. DrawLine (new Pen (Color. Silver), x1, y1, x2, y2 );
}

// The font of the verification code in the output image: Arial on the 12th, bold and italic.
Font font = new System. Drawing. Font ("Arial", 12, (System. Drawing. FontStyle. Bold | System. Drawing. FontStyle. Italic ));
System. Drawing. Drawing2D. LinearGradientBrush brush = new System. Drawing. Drawing2D. LinearGradientBrush (
New Rectangle (0, 0, image. Width, image. Height ),
Color. Blue,
Color. DarkRed,
1.2f,
True );
G. DrawString (checkCode, font, brush, 2, 2 );

// Picture foreground noise: 50
For (int I = 0; I <50; 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. SaddleBrown ),
0,
0,
Image. Width-1,
Image. Height-1 );

// Create a memory stream for outputting Images
System. IO. MemoryStream MS = new System. IO. MemoryStream ();
Image. Save (MS, System. Drawing. Imaging. ImageFormat. Gif );
Response. ClearContent ();
Response. ContentType = "image/Gif ";
Response. BinaryWrite (ms. ToArray ());
}
Finally
{
G. Dispose ();
Image. Dispose ();
}
}

}

Next, add the HTML tag at the location where the verification code is used, set the "src" attribute to "RandomImage. aspx", and
Add the following verification code in the background:
Protected void button#click (object sender, EventArgs e)
{
// Check the verification code
If (Request. Cookies ["CheckCode"] = null)
{
Label2.Visible = true;
Label2.Text = "your system disables Cookies, so you cannot use the verification code ";
Return;
}
// Check whether the entered verification code is correct
If (string. Compare (Request. Cookies ["CheckCode"]. Value, TextBox6.Text, true )! = 0)
{
Label2.Text = "the verification code is incorrect. Enter the correct verification code! ";
Label2.Visible = true;
Return;
}
... // Omitted the data added to the database
}

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.