How does ASP. NET make a simple verification code? asp.net makes the verification code.

Source: Internet
Author: User

How does ASP. NET make a simple verification code? asp.net makes the verification code.

If you want to do the verification code, you have to mention the GDI + plot. We all know that the verification code is displayed in the form of images and is dynamically generated, so we need to draw it.

What is GDI +?

GDI + is an advanced version of the graphic device interface (GDI). It provides a variety of graphic image processing functions. GDI + consists of two-dimensional vector graphics, image processing, and layout. GDI + provides a lot of support for complex tasks such as displaying text with various fonts, font sizes, and styles.

Let's talk about the Verification Code. For an image like the verification code, I think it is composed of two parts, one of which is the background of the rectangle, another part is the combination of letters and numbers (sometimes there are Chinese characters, sometimes pure letters or numbers, there is no uniform rule, how to choose to look at you ~). For the background of a rectangle, we can directly regard it as a canvas, a combination of letters and numbers? We can use random numbers to spell out a new combination. In this way, we have thought about the whole process. Let's look at the code below:

I wrote this verification code with a length of 5 characters. It consists of uppercase and lowercase English letters and numbers.

Private readonly char [] constant = {'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', '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'}; // a character array consisting of numbers and uppercase/lowercase letters protected void Page_Load (object sender, EventArgs e) {Bitmap bitmap = new Bitmap (100, 25); // create a Bitmap with a width of 100 and a height of 25. This is what I call the first part. The rectangular background Graphics g = Graphics. fromImage (bitmap); // create a canvas g. clear (Color. yellowGreen); // fill the canvas with yellow/green Font font1 = new Font ("Arial", 15); // set the Font type and size. Brush = new SolidBrush (Color. blue); // set the paint brush Color Pen myPen = new Pen (Color. blue, 5); // create the paint brush object StringBuilder random = new StringBuilder (5); // create a variable String object to store the randomly generated Verification Code Random rd = new Random (); // create a random number generator object for (int I = 0; I <random. capacity; I ++) {random. append (constant [rd. next (62)]); // generate a random character and add it to the random} g. drawString (random. toString (), font1, brush, 10, 5); // draw the System string on the canvas. IO. memoryStream MS = new System. IO. memoryStream (); // create a data stream MemoryStream bitmap. save (MS, System. drawing. imaging. imageFormat. gif); // specify the output format of the image as gif Response. clearContent (); Response. contentType = "image/Gif"; Response. binaryWrite (ms. toArray (); // output binary data stream}

The generated results are as follows:

It may seem easy to recognize, which is similar to the Verification code we enter when logging on to the website. Of course, we can make some changes.

Private readonly char [] constant = {'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', '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'}; // a character array consisting of numbers and uppercase/lowercase letters protected void Page_Load (object sender, EventArgs e) {Bitmap bitmap = new Bitmap (100, 25); // create a Bitmap with a width of 100 and a height of 25. This is what I call the first part. The rectangular background Graphics g = Graphics. fromImage (bitmap); // create a canvas g. clear (Color. yellowGreen); // fill the canvas with yellow-green Font font1 = new Font ("Arial", 15); // set the Font type and size float angle = 60; // rotate a base angle float length = 0; // display the base position of the character, and then look at the Brush brush = new SolidBrush (Color. blue); // set the paint brush Color Pen myPen = new Pen (Color. blue, 5); // create the paint brush object StringBuilder random = new StringBuilder (5); // create a variable String object to store the randomly generated Verification Code Random rd = new Random (); // create a random number generator object for (int I = 0; I <random. capacity; I ++) {random. append (constant [rd. next (62)]); // generate a random character and add it to the random g. resetTransform (); // reset the canvas matrix SizeF size = g. measureString (random [random. length-1]. toString (), font1); // obtain the new size g. translateTransform (length + size. width/2, size. height/2); // select the center of the rotation g. rotateTransform (float) rd. nextDouble () * angle * 2-angle); // rotate g at random angles. drawString (random [random. length-1]. toString (), font1, brush, new PointF (-size. width/2,-size. height/2); // note: this is not the previous example. You can draw all five characters at a time, but one by one length + = size. width; // ensure that the position of the next character will not overwrite the previous character} System. IO. memoryStream MS = new System. IO. memoryStream (); // create a data stream MemoryStream bitmap. save (MS, System. drawing. imaging. imageFormat. gif); // specify the output format of the image as gif Response. clearContent (); Response. contentType = "image/Gif"; Response. binaryWrite (ms. toArray (); // output binary data stream}

The generated result is as follows:

Does it look more professional? If you are still dissatisfied, you can check the content related to GDI + to improve the recognition difficulty by adding some noise elements or deleting such items, I will not list them here.

We have said about how to draw a verification code, but I still want to talk about two more questions.

1. What we actually output is a binary stream. How can we display it on a page and coexist with other elements on the page?

Here, a common method is to place the code for the verification code into an independent Web form page, and put a element on another page that requires the verification code to be displayed, point the src property to the url of the verification code page. For example

<asp:Image ID="image_validatecode" runat="server" ImageUrl="~/PublicMethod/ValidateCode.aspx" style="padding-left:3px"/>

In fact, I use a common method here. However, I previously wrote a web custom control to generate a verification code. However, when it is dragged to the page, it runs, it will overwrite other elements of the page. I am not sure the specific reason.

2. The verification code is mainly used for verification. Therefore, in addition to the username and password, we also need to determine whether the entered verification code is consistent with the verification code on the image.

I did not write this block in the above Code. In fact, you only need to save the value to a session after the final verification code is randomly generated. Then, when determining the user name and password, it is OK to compare the session value. For example:

Session["login_validate_code"] = random.ToString();

3. How can I change the verification code to another one?

You can use a script to assign a url value to the src attribute of the img element. You can also use ajax to implement this if you are in trouble. You can try it on your own.


How does ASPNET design a simple verification code?

Create an Image. aspx page without adding any elements to the foreground. The background code is
Static readonly string STR = "0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz ";

Protected void Page_Load (object sender, EventArgs e)
{
Random rd = new Random ();
Int a = rd. Next (100 );
Int B = rd. Next (1000 );
Int m = rd. Next (10000 );
Int n = rd. Next (100000 );
String result = STR. Substring (a % 62, 1 );
Result + = STR. Substring (B % 62, 1 );
Result + = STR. Substring (m % 62, 1 );
Result + = STR. Substring (n % 62, 1 );

Session ["check"] = result;
CreateImage (result );

}
/// <Summary>
/// Create a verification image for the specified content and output it
/// </Summary>
/// <Param name = "content"> </param>
Private void CreateImage (string content)
{
// Judge whether the string is not equal to null or null
If (content = null | content. Trim () = String. Empty)
Return;
// Create a bitmap object
Bitmap image = new Bitmap (int) Math. Ceiling (content. Length * 12.5), 22 );
// Create Graphics
Graphics g = Graphics. FromImage (image );
Try
{
// Generate a random Generator
Random random = new Random ();
// Clear the background color of the image.
G. Clear (Color. White );
// Draw the background interference line of the image
For (int I = 0; I <2; I ++)
{
Int x1 = random. Next (image. Width );
Int x2 = ra... the remaining full text>

Create an ASPNET Verification Code

Display the verification code page (front-end)

<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "AdminLogin. aspx. cs" Inherits = "Admin_AdminLogin" %>
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "www.w3.org/..al.dtd">
<Html xmlns = "www.w3.org/5o/xhtml">
<Head runat = "server">
<Title> Admin Logon </title>
<Script type = "text/javascript">
Function changeimg (){
Var myimg = document. getElementById ("img_Check ");
Now = new Date (); // if this event is not set, a bug can only be changed once.
Myimg. src = "AdminImage. aspx? Code = "+ now. getTime ();
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div align = "center">
<Table>
<Tr>
<Td align = "right">
Verification Code: <asp: TextBox ID = "tb_Check" runat = "server" Width = "70"> </asp: TextBox>
<Asp: Image ID = "img_Check" runat = "server" ImageUrl = "~ /Admin/AdminImage. aspx "Vis... the remaining full text>

Related Article

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.