First, add an image control to the login. aspx interface. The imageurl points to validatecode. aspx.
Validatecode. aspx is used to generate a verification code. Page_load is as follows:
Private void page_load (Object sender, system. eventargs E)
{
String checkcode = createrandomcode (4 );
Session ["checkcode"] = checkcode;
Createimage (checkcode );
}
Two functions are defined. createrandomcode generates a verification code and createimage enters it to the page. The session verification code is used to determine whether the input of the verification code is correct.
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;
}
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. darkblue );
G. Clear (color. White );
G. drawstring (checkcode, F, B, 3, 3 );
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 ();
}