. NET uses a general handler to generate a verification code

Source: Internet
Author: User

This verification code is expected to be used in the future, so I transferred this article to enrich the code base.

Last run:

 

 

HTML code:


[Html]
<! --
Document: ASP. NET uses a general processing program to generate a verification code
Created on:
Author: Ox's nest
-->
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Title> </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Script type = "text/javascript">
Function change (){
Var imgNode = document. getElementById ("vimg ");
ImgNode. src = "WaterMark. ashx? T = "+ (new Date (). valueOf (); // here, a time parameter is added to prevent browser cache problems.
}
</Script>
</Head>
<Body>
<input type =" button "value =" change image "onclick =" change () "/>
</Body>
</Html>
<! --
Document: ASP. NET uses a general processing program to generate a verification code
Created on:
Author: Ox's nest
-->
<! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN">
<Html>
<Head>
<Title> </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Script type = "text/javascript">
Function change (){
Var imgNode = document. getElementById ("vimg ");
ImgNode. src = "WaterMark. ashx? T = "+ (new Date (). valueOf (); // here, a time parameter is added to prevent browser cache problems.
}
</Script>
</Head>
<Body>
<input type =" button "value =" change image "onclick =" change () "/>
</Body>
</Html>

 


The code of the general processing program WaterMark. ashx:


[Csharp]
<% @ WebHandler Language = "C #" Class = "WaterMark" %>
 
Using System;
Using System. Web;
Using System. Drawing;
Using System. Drawing. Drawing2D;
Using System. Web. SessionState;
 
Public class WaterMark: IHttpHandler, IRequiresSessionState // You must implement this interface to use session. Remember to import the System. Web. SessionState namespace
{
 
Public void ProcessRequest (HttpContext context)
{
String checkCode = GenCode (5); // generates 5 random characters
Context. Session ["Code"] = checkCode; // Save the string to the Session for verification as needed
System. Drawing. Bitmap image = new System. Drawing. Bitmap (70, 22 );
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 noise line of the image
Int I;
For (I = 0; I <25; I ++)
{
Int x1 = random. Next (image. Width );
Int x2 = random. Next (image. Width );
Int y1 = random. Next (image. Height );
Int y2 = random. Next (image. Height );
G. DrawLine (new Pen (Color. Silver), x1, y1, x2, y2 );
}
 
Font font = new System. Drawing. Font ("Arial", 12, (System. Drawing. FontStyle. Bold ));
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 );
G. DrawString (checkCode, font, brush, 2, 2 );
 
// Foreground noise of the image
G. DrawRectangle (new Pen (Color. Silver), 0, 0, image. Width-1, image. Height-1 );
System. IO. MemoryStream MS = new System. IO. MemoryStream ();
Image. Save (MS, System. Drawing. Imaging. ImageFormat. Gif );
Context. Response. ClearContent ();
Context. Response. ContentType = "image/Gif ";
Context. Response. BinaryWrite (ms. ToArray ());
}
Finally
{
G. Dispose ();
Image. Dispose ();
}
}
 
/// <Summary>
/// Generate a random string
/// </Summary>
/// <Param name = "num"> several random characters </param>
/// <Returns> random string </returns>
Private string GenCode (int num)
{
String str = "0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ "; // "One thing is that when I want someone to give birth to a place, I will be able to share my work with others. next, let's talk about how to produce seeds. After that, let's talk about how to implement the study law. The people go through the 13th, and wait for the power of the Ministry to turn the water into water, and then take advantage of the two mechanisms to increase the actual amount of small things. click the job book to better enable it because it is still caused by some of its previous days, the four days before the day, the social and social affairs are in the form of a full table between the sample and the close of the various re-line inside the number of the heart against your understanding look at the original product or product, but the quality of the first to the fate of this change only did not solve the problem that the idea of the creation of the month, no army, the most beautiful generation of hope has been passed and raised straight question party Cheng Zhan five fruit elephant staff leather position into the common text of the total product type active settings and management of the special piece of long request old man-Based Edge stream road level less tushan transport knowledge will be compared to the group to see his hand corner of the root theory Yun Nong it refers to the number of nine zones in which the West Region is forced to fight, the first battle is required, then the data retrieval team south to the color door, that is, to protect the North to create a hundred rules hot collar seven sea port East guide pressure zhi Shi Jin Zeng jixian oil thinking skills highly subject to the joint recognition of the six total rights to receive certificates to clear their beauty and then mining more single wind cut hit white teach fast flowers with an on-site car examples of real affairs each item reaches the product presentation report class eight from the Chinese name really only section Zhang xinma festival words rice whole empty yuan situation this collection temperature transfer soil Xu Bu group wide stone note needs section research circle Lilin Law call and research view the more weaving and installation of shadows, the Low Holding voices, the public book, the complex content, the inter-business non-verification, the disconnections, the deep difficulty, the recent mining Week, the technical support, the semi-office, the province, the train about zhizhishishixinlaobaotuan to the acid city Ke he in addition to the structure of the government called too quasi precise value number rate family planning selection mark write stored in the Mao xiankuaiyunshu jianjiang eye wang raised according to the age easy to set school film began but specialized breeding factory Beijing knowledge belongs to the Round bag fire live adjustable full county bureau according to the red fine cited listen to the iron price Yan ";
Char [] chastr = str. ToCharArray ();
// 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 ","#", "{1} quot;," % ","&","@"};
String code = "";
Random rd = new Random ();
Int I;
For (I = 0; I <num; I ++)
{
// Code + = source [rd. Next (0, source. Length)];
Code + = str. Substring (rd. Next (0, str. Length), 1 );
}
Return code;
 
}
 
Public bool IsReusable
{
Get
{
Return false;
}
}
 
}
<% @ WebHandler Language = "C #" Class = "WaterMark" %>

Using System;
Using System. Web;
Using System. Drawing;
Using System. Drawing. Drawing2D;
Using System. Web. SessionState;

Public class WaterMark: IHttpHandler, IRequiresSessionState // You must implement this interface to use session. Remember to import the System. Web. SessionState namespace
{

Public void ProcessRequest (HttpContext context)
{
String checkCode = GenCode (5); // generates 5 random characters
Context. Session ["Code"] = checkCode; // Save the string to the Session for verification as needed
System. Drawing. Bitmap image = new System. Drawing. Bitmap (70, 22 );
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 noise line of the image
Int I;
For (I = 0; I <25; I ++)
{
Int x1 = random. Next (image. Width );
Int x2 = random. Next (image. Width );
Int y1 = random. Next (image. Height );
Int y2 = random. Next (image. Height );
G. DrawLine (new Pen (Color. Silver), x1, y1, x2, y2 );
}

Font font = new System. Drawing. Font ("Arial", 12, (System. Drawing. FontStyle. Bold ));
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 );
G. DrawString (checkCode, font, brush, 2, 2 );

// Foreground noise of the image
G. DrawRectangle (new Pen (Color. Silver), 0, 0, image. Width-1, image. Height-1 );
System. IO. MemoryStream MS = new System. IO. MemoryStream ();
Image. Save (MS, System. Drawing. Imaging. ImageFormat. Gif );
Context. Response. ClearContent ();
Context. Response. ContentType = "image/Gif ";
Context. Response. BinaryWrite (ms. ToArray ());
}
Finally
{
G. Dispose ();
Image. Dispose ();
}
}

/// <Summary>
/// Generate a random string
/// </Summary>
/// <Param name = "num"> several random characters </param>
/// <Returns> random string </returns>
Private string GenCode (int num)
{
String str = "0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ "; // "One thing is that when I want someone to give birth to a place, I will be able to share my work with others. next, let's talk about how to produce seeds. After that, let's talk about how to implement the study law. The people go through the 13th, and wait for the power of the Ministry to turn the water into water, and then take advantage of the two mechanisms to increase the actual amount of small things. click the job book to better enable it because it is still caused by some of its previous days, the four days before the day, the social and social affairs are in the form of a full table between the sample and the close of the various re-line inside the number of the heart against your understanding look at the original product or product, but the quality of the first to the fate of this change only did not solve the problem that the idea of the creation of the month, no army, the most beautiful generation of hope has been passed and raised straight question party Cheng Zhan five fruit elephant staff leather position into the common text of the total product type active settings and management of the special piece of long request old man-Based Edge stream road level less tushan transport knowledge will be compared to the group to see his hand corner of the root theory Yun Nong it refers to the number of nine zones in which the West Region is forced to fight, the first battle is required, then the data retrieval team south to the color door, that is, to protect the North to create a hundred rules hot collar seven sea port East guide pressure zhi Shi Jin Zeng jixian oil thinking skills highly subject to the joint recognition of the six total rights to receive certificates to clear their beauty and then mining more single wind cut hit white teach fast flowers with an on-site car examples of real affairs each item reaches the product presentation report class eight from the Chinese name really only section Zhang xinma festival words rice whole empty yuan situation this collection temperature transfer soil Xu Bu group wide stone note needs section research circle Lilin Law call and research view the more weaving and installation of shadows, the Low Holding voices, the public book, the complex content, the inter-business non-verification, the disconnections, the deep difficulty, the recent mining Week, the technical support, the semi-office, the province, the train about zhizhishishixinlaobaotuan to the acid city Ke he in addition to the structure of the government called too quasi precise value number rate family planning selection mark write stored in the Mao xiankuaiyunshu jianjiang eye wang raised according to the age easy to set school film began but specialized breeding factory Beijing knowledge belongs to the Round bag fire live adjustable full county bureau according to the red fine cited listen to the iron price Yan ";
Char [] chastr = str. ToCharArray ();
// 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 ","#", "{1} quot;," % ","&","@"};
String code = "";
Random rd = new Random ();
Int I;
For (I = 0; I <num; I ++)
{
// Code + = source [rd. Next (0, source. Length)];
Code + = str. Substring (rd. Next (0, str. Length), 1 );
}
Return code;

}

Public bool IsReusable
{
Get
{
Return false;
}
}

}

From jarin's column
 

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.