How to generate a verification code Asp.net

Source: Internet
Author: User

Today, I searched the internet for how to generate a Verification Code. There are many examples. I read an article and have a rough understanding of it.

I don't know much about. Net classes, such as bitmap. I can only do it based on others. He uses VB. NET to do this. I can only use C # Instead of VB.net.

Create a web project, and create a web form named GIF. aspx.

Build Method

Private void createpic (string Str)
{
System. Drawing. bitmap BMP;
System. Drawing. Graphics g;
System. Io. memorystream MS;

// I still don't understand why I want to do this. I will take a look at the tutorial later.

Int piclen = Str. length * 12;

BMP = new Bitmap (piclen, 20 );
G = system. Drawing. Graphics. fromimage (BMP );
G. drawstring (STR, (new font ("Arial", 12), (new solidbrush (color. Blue), 1, 1 );

MS = new system. Io. memorystream ();
BMP. Save (MS, imageformat. PNG );
Response. clearcontent ();
Response. contenttype = "image/PNG ";
Response. binarywrite (Ms. toarray ());

G. Dispose ();
BMP. Dispose ();
Response. End ();

}

Create a method to generate random numbers

Private string createrandomiz (int n)
{
System. Random r = new random ();
String STR = ", Q, W, E, R, T, Y, U, I, O, P, A, S, D, f, G, H, J, K, L, Z, X, C, V, B, n, m ";
Char [] A = new char [1];
A [0] = ',';

String [] str1 = Str. Split ();
String temp = "";
For (INT I = 0; I <n; I ++)
{

Temp = temp + str1 [R. Next (35)]. tostring ();

}
Return temp;
}

 

Then you can call it in page_load.
Private void page_load (Object sender, system. eventargs E)
{
String num = This. createrandomiz (4); // generates four random numbers.
Session ["A"] = num; // use session to save
This. createpic (Num );
}

Add an image Web Server Control to webform1 to set the imageurl to gif. aspx.
Drag and Drop a button and a textbox
Write in button

If (this. textbox1.text! = Session ["A"]. tostring ())
{
Response. Write ("error ");
}
Else
{
Response. Write ("OK ");
}

 

This completes. Continue to read the tutorial.

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.