Detailed description of how to generate a verification code-ASP. NET details (4) and asp.net details
Preface
Today, I want to explain in detail all the issues with the verification code generated during ASP. NET Website development.
The goal of this article is to let readers understand all the basic knowledge issues involved in generating verification codes.
Of course, this is a simple verification code.
The verification code that truly meets the requirements involves some computer graphics issues. This is not something that should be considered by website developers. The company must have a dedicated person to do this or develop packages.
1.Why study this?
Before the beginning of the text, I want to emphasize a few more questions.
1. If you have no idea about how to generate a verification code, development will not be affected.
We can use the C + vcode on the Internet (that is to say, this is not the core issue of asp.net website development ).
Frankly speaking, I cannot remember what I wrote today.
2. However, xiaobian has a habit. If I don't understand a piece of code at all.
So even if I knew that it could be used after he pasted it, I was not very steadfast.
Therefore, you can't write it out, but you must understand it and be steadfast in your mind.
2. Learning Process
The learning process in this article is arranged in this way.
So let's start
A simple use case of GDI
1. Description
If you want to think about how to generate a verification code, the first problem you need to solve is,
It must be that. NET dynamically generates images. (Even if you know it)
// GDI: Some plotting classes in the. Net program.
2.Code
1 // Add a reference to System. Drawing before this code starts. 2 // create a memory image with a size of 500*500 3 using (Bitmap bmp = new Bitmap (500,500) 4 // obtain the image canvas 5 using (Graphics g = Graphics. fromImage (bmp) 6 {7 // create paint brush 8 using (Font font = new Font (FontFamily. genericSerif, 30) 9 {10 // draw a red helloWorld11 g at 100,100. drawString ("HelloWorld", font, Brushes. red, 100,100); 12 // draw a blue 13g ellipse at 100,100. drawEllipse (Pens. blue, 100,100,100,100); 14 15 using (Stream stream = File. openWrite (@ "d: \ 2.jpg") 16 {17 bmp. save (stream, ImageFormat. jpeg); 18} 19} 20}
Now the generation is complete. There seems to be nothing to explain in the code.
Returns an image using a general processing program.
1.Description
Next we will study how to dynamically generate an image on the webpage.
From the code point of view. There are only a few simple differences with the code on the console above, almost the same!
1) In general, you need to set ContentType = "image/jpeg" first"
2) The general processing program needs to save the image to Response. OutputStream.
2.Code
1 context. Response. ContentType = "image/jpeg"; 2 3 // Add a reference to System. Drawing before starting this code. 4 // create a memory image 5 using (Bitmap bmp = new Bitmap (500) with a size of 500*500,500. 6 // obtain the image canvas 7 using (Graphics g = Graphics. fromImage (bmp) 8 {9 // create paint brush 10 using (Font font = new Font (FontFamily. genericSerif, 30) 11 {12 // draw a red helloWorld13 g at 100,100. drawString ("HelloWorld", font, Brushes. red, 100,100); 14 // draw a blue oval 15g at 100,100. drawEllipse (Pens. blue, 100,100,100,100); 16 // Save the image to the output stream 17 bmp. save (context. response. outputStream, ImageFormat. jpeg); 18 19} 20}
Simple Digital Verification Code
1.Thinking
Since we have solved the problem of how to dynamically generate images and how to return an image in a general processing program.
The technical problem of verification code is how to generate four random numbers.
In fact, Random is used to generate 1000 ~ A random number between 9999.
Then, put the four digits in the Session and generate the verification code Image Based on the number.
This is the basic logic for generating verification codes.
2.Code
1 public void ProcessRequest (HttpContext context) 2 {3 context. response. contentType = "image/jpeg"; 4 5 Random random = new Random (); 6 // generate a random number 7 string code = Random. next (1000,999 9 ). toString (); 8 // place the verification code in the Session to facilitate later comparison of 9 context. session ["checkCode"] = code; 10 // The image 11 using (Bitmap bmp = new Bitmap (130, 50) 12 using (Graphics g = Graphics. fromImage (bmp) 13 {14 using (Font font = new Font (FontFamily. genericSerif, 30) 15 {16g. drawString (code, font, Brushes. aliceBlue, 10, 10); 17 // Save the image to the output stream 18 bmp. save (context. response. outputStream, ImageFormat. jpeg); 19} 20} 21}
Generate results (of course, this verification code can be read by anyone who knows a little bit about graphics, and never do so during Development !)
3. Out-of-band branches
I was so happy to sing this song on the Code. The result suddenly gave me an exception of empty reference. It is necessary to mention it here.
It seems necessary to write an article, introduce the Session in detail, and make up a supplementary lesson for yourself.
A slightly more complex verification code
1. Ideas
The verification code above is too simple. Now it is a little more complicated.
My idea for improvement is as follows.
1) Since it is too simple to generate a random number, I cannot say it. Then, five characters are randomly generated.
Characters are written in an array. Randomly generate the array subscript, and then take out five. Character array we can write a little more complex.
2) After an image is generated, you can easily throw a click on the image to increase the recognition cost of other programs.
2. Code
1 public void ProcessRequest (HttpContext context) 2 {3 string checkCode = GenCode (5); // generates 5 random characters 4 context. session ["Code"] = checkCode; // Save the string to the Session so that verification is performed if necessary. drawing. bitmap image = new System. drawing. bitmap (70, 22); 6 Graphics g = Graphics. fromImage (image); 7 try 8 {9 // generate Random generator 10 random Random = new Random (); 11 // clear image background color 12g. clear (Color. white); 13 // the background noise line of the picture 14 int I; 15 for (I = 0; I <25; I ++) 16 {17 int x1 = random. next (image. width); 18 int x2 = random. next (image. width); 19 int y1 = random. next (image. height); 20 int y2 = random. next (image. height); 21g. drawLine (new Pen (Color. silver), x1, y1, x2, y2); 22} 23 24 Font font = new System. drawing. font ("Arial", 12, (System. drawing. fontStyle. bold); 25 System. drawing. drawing2D. linearGradientBrush brush = new System. drawing. drawing2D. linearGradientBrush (new Rectangle (0, 0, image. width, image. height), Color. blue, Color. darkRed, 1.2F, true); 26g. drawString (checkCode, font, brush, 2, 2); 27 // foreground noise of the picture to draw 28 GB. drawRectangle (new Pen (Color. silver), 0, 0, image. width-1, image. height-1); 29 System. IO. memoryStream MS = new System. IO. memoryStream (); 30 image. save (MS, System. drawing. imaging. imageFormat. gif); 31 context. response. clearContent (); 32 context. response. contentType = "image/Gif"; 33 context. response. binaryWrite (ms. toArray (); 34} 35 finally 36 {37g. dispose (); 38 image. dispose (); 39} 40} 41 42 // <summary> 43 // generate a random string 44 // </summary> 45 // <param name = "num"> random returns a few characters </param> 46 // <returns> random string </returns> 47 private string GenCode (int num) 48 {49 string str = "0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 50 char [] chastr = str. toCharArray (); 51 // string [] source = {"0", "1", "2", "3", "4", "5 ", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F ", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P ", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z ", "#", "$", "%", "&", "@"}; 52 string code = ""; 53 Random rd = new Random (); 54 int I; 55 for (I = 0; I <num; I ++) 56 {57 // code + = source [rd. next (0, source. length)]; 58 code + = str. substring (rd. next (0, str. length), 1); 59} 60 return code; 61}
Generate results. Can it be used almost?
Now let's talk about the verification code today.
In my opinion, there is no need to remember this kind of things. Of course, if you can get started with it, it would be excellent.
I can't remember it and it doesn't affect development. I just need to search for it online when I write it.
There are two reasons for writing this article.
1) there are always people who want to write such things, or where to copy them.You can also find it after writing an article by yourself.
2) code that is unknown can be used even if it is copied,However, it is useless.
(Of course, this is not absolute. If it is too difficult, forget it. There are still too many thingsWe do not need to know.)