Generate a verification code in ASP. NET (C #)

Source: Internet
Author: User

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 ();

}

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.