In some projects, you need to prompt the user to enter the verification code when registering or logging on. How can you implement the verification code function in ASP. NET?
1. Knowledge Point Introduction
The verification code is actually a random number. The random class provided in the system namespace can be used to generate random non-negative numbers.
In ASP.. net. the drawing namespace provides bitmap and graphics classes. The bitmap class encapsulates the GDI + bitmap class and inherits from the image class to process images defined by pixel data. the graphics class encapsulates the GDI and drawing surface, which is equivalent to the drawing board. the following uses the random, bitmap, and graphics classes to draw the generated number to the created bitmap. use the image control to display the created bitmap.
2. Example
Create a "webform1.aspx" Page, add an image control to the page, and set its imageurl attribute to the path to store the generated bitmap.
(1) webform1.aspx. CS Code : Private Void Page_load ( Object Sender, system. eventargs E)
{
// Create a bitmap object
Bitmap newbitmap = New Bitmap ( 36 , 16 , System. Drawing. imaging. pixelformat. format32bppargb );
// Create a drawing layer based on the previously created bitmap object
Graphics g = Graphics. fromimage (newbitmap );
// Fill in the pet rectangle area with the specified color
G. fillrectangle ( New Solidbrush (color. White ), New Rectangle ( 0 , 0 , 36 , 16 ));
// Create a font object
Font textfont = New Font ( " Times New Roman " , 10 );
// Create a rectanglef structure to specify a region
Rectanglef rectangle = New Rectanglef ( 0 , 0 , 36 , 16 );
// Create random number object
Random Rd = New Random ();
// Obtain Random Number
Int Valationno = 1000 + Rd. Next ( 8999 );
// Fill the area of the rectangle specified by the rectanglef structure above with the specified color
G. fillrectangle ( New Solidbrush (color. burlywood), rectangle );
// Fill in the above-filled rectangular area with the random number generated above
G. drawstring (valationno. tostring (), textfont, New Solidbrush (color. Blue), rectangle );
// Save the created bitmap to the specified path.
Newbitmap. Save (server. mappath ( " IMG " ) + " \ Randomimg.gif " , System. Drawing. imaging. imageformat. GIF );
}
(2) Code Description
first, create bitmap and graphics objects, and then draw random numbers generated by the random object into the map using the font and rectanglef objects, finally, save the created bitmap to the specified directory.
Note: first run the Program program.