Create ValidateCode. aspx
Its Background cs file code is as follows:
PageLoad
Private void Page_Load (object sender, System. EventArgs e)
{
String checkCode = CreateRandomCode (4 );
Session ["CheckCode"] = checkCode;
CreateImage (checkCode );
}
CreateRandomCode is a custom function, and the parameter represents the number of digits of the verification code.
Private string CreateRandomCode (int codeCount)
{
String allChar = ", A, B, C, D, E, F, G, H, I, J, K, L, M, n, O, P, Q, R, S, T, U, W, X, Y, Z ";
String [] allCharArray = allChar. Split (',');
String randomCode = "";
Int temp =-1;
Random rand = new Random ();
For (int I = 0; I <codeCount; I ++)
{
If (temp! =-1)
{
Rand = new Random (I * temp * (int) DateTime. Now. Ticks ));
}
Int t = rand. Next (35 );
If (temp = t)
{
Return CreateRandomCode (codeCount );
}
Temp = t;
RandomCode + = allCharArray [t];
}
Return randomCode;
}
CreateImage is also a custom function used to generate graphs.
Private void CreateImage (string checkCode)
{
Int iwidth = (int) (checkCode. Length * 11.5 );
System. Drawing. Bitmap image = new System. Drawing. Bitmap (iwidth, 20 );
Graphics g = Graphics. FromImage (image );
Font f = new System. Drawing. Font ("Arial", 10, System. Drawing. FontStyle. Bold );
Brush B = new System. Drawing. SolidBrush (Color. White );
// G. FillRectangle (new System. Drawing. SolidBrush (Color. Blue), 0, 0, image. Width, image. Height );
G. Clear (Color. Blue );
G. DrawString (checkCode, f, B, 3, 3 );
Pen blackPen = new Pen (Color. Black, 0 );
Random rand = new Random ();
For (int I = 0; I <5; I ++)
{
Int y = rand. Next (image. Height );
G. DrawLine (blackPen, 0, y, image. Width, y );
}
System. IO. MemoryStream MS = new System. IO. MemoryStream ();
Image. Save (MS, System. Drawing. Imaging. ImageFormat. Jpeg );
Response. ClearContent ();
Response. ContentType = "image/Jpeg ";
Response. BinaryWrite (ms. ToArray ());
G. Dispose ();
Image. Dispose ();
}
// G. FillRectangle (new System. Drawing. SolidBrush (Color. Blue), 0, 0, image. Width, image. Height );
G. Clear (Color. Blue );
Both methods can change the background color of the generated image.
The for loop below is used to generate random horizontal lines.
Add an <asp: Image> control on the page that requires the verification code, but point the ImageUrl to the page that generates the verification code.
<Asp: Image Runat = "server" ID = "ImageCheck" ImageUrl = "ValidateCode. aspx"> </asp: Image>