ASP. NET custom verification code control

Source: Internet
Author: User

Recently I wrote a custom verification code control to share it with you.

Procedure

1 --- create an Asp.net website

2 --- Add a new project and select a class library

3 --- create two classes

3.1 -- custom control class (webcontrol derived class)

Using system;
Using system. Collections. Generic;
Using system. componentmodel;
Using system. LINQ;
Using system. text;
Using system. Web;
Using system. Web. UI;
Using system. Web. UI. webcontrols;

Namespace authcode
{
[Toolboxdata ("<{ 0}: authcode runat = Server> </{0}: authcode>")]
Public class authcode: webcontrol
{
/// <Summary>
/// Obtain the verification code value
/// </Summary>
/// <Returns> Verification Code </returns>
Public String getvalue ()
{
Return httpcontext. Current. session ["value"]. tostring ();
}
[Bindable (true)]
[Category ("appearance")]
[Description ("Verification Code character length")]
[Defaultvalue ("SS")]
[Localizable (true)]
// Length
Internal static int mysize;

Public int mysize
{< br> get {return authcode. mysize ;}< br> set
{< br> authcode. mysize = value;

}< BR >}< br>

Public authcode ()
: Base (htmltextwritertag. IMG) // rewrite the structure of the parent class (HTML tag of the output stream)
{}< br> protected override void addattributestorender (htmltextwriter writer)
{< br> base. addattributestorender (writer); // Add the attributes and styles of the HTML tag to be output to the specified htmltextwriter.
writer. addstyleattribute (htmltextwriterstyle. cursor, "Pointer"); // Add a style

/**-
* onclick event of the image "This. src = 'verifyimg. JD? Id = '+ math. Random () "
* a new image Request Path (verifyimg. JD? Id = '+ math. the random () parameter is only
* tells the browser that this is a new request and is processed by ihttphander to generate a new image ID, which has no actual meaning (create a new request)
*-**/
writer. addattribute ("onclick", "this. src = 'img. JD? Id = '+ math. Random () "); // Add JS verifyimg. JD

Writer. addattribute (htmltextwriterattribute. SRC, "IMG. JD ");
Writer. addattribute ("Alt", "click to refresh ");
}

}
}
 

3.2 -- create a processing class (the ihttphandler and irequiressessionstate interfaces must be implemented)

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using system. Web;
Using system. Web. UI. webcontrols;
Using system. Web. UI;
Using system. Web. sessionstate;
Using system. drawing;
Using system. IO;

Namespace authcode
{
Public class authcodehttphander: ihttphandler, irequiressessionstate
{
/// <Summary>
/// Return verification code characters
/// </Summary>
/// <Param name = "codecount"> Verification code length </param>
/// <Returns> </returns>
Private string getrandomnumberstring (INT codecount)
{
String strchoice = "2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, G, H, J, K, L, M, N, P, q, R, S, T, U, V, W, X, Y, Z ";
String [] strresult = strchoice. Split (New char [] {','});
String strreturn = "";
Random RND = new random ();
For (INT I = 0; I <codecount; I ++)
{
Int J = RND. Next (strresult. Length); // the random number cannot exceed the length of the array.
Strreturn = strreturn + strresult [J]. tostring ();
}
Return strreturn;
}

Private color getcolor ()
{
Return color. Black;
}
Private bitmap createimage (string str_authcode)
{
/* ----------------------------- Draw the image style ------------------------------------*/

Int width = str_authcode.length * 21;
Int Height = 30;
Random rad = new random ();
Bitmap BMP = new Bitmap (width, height );
Graphics GRP = graphics. fromimage (BMP); // draw the image
GRP. Clear (color. yellowgreen); // fill in the background color of BMP.
GRP. drawrectangle (new pen (color. Red, 1), 0, 0, width-1, height-1); // draw a border
Int num = width * height;
For (INT I = 0; I <num; I ++) // draw a colored dot on the specified coordinate of the image
{
Int x = rad. Next (width );
Int y = rad. Next (height );
Int r = rad. Next (255 );
Int G = rad. Next (255 );
Int B = rad. Next (255 );
Color c = color. fromargb (R, G, B );
BMP. setpixel (X, Y, c); // draw colored dots on the specified coordinates of the image.
}

/* -------------------------- Draw a string in the image ------------------------------------*/

Font F = new font ("", 20, fontstyle. Bold); // define the font
Brush BR = new solidbrush (color. Black); // defines the color of the paint brush and the color of the font.
For (INT I = 0; I <str_authcode.length; I ++)
{
String S = str_authcode.substring (I, 1); // draw a single image
Point P = new point (I * 20 + rad. Next (3), Rad. Next (3) + 1); // the position where the font appears (coordinates)
GRP. drawstring (S, F, BR, P); // draw a string
}
GRP. Dispose ();
Return BMP; // return

}

/// <Summary>
/// Whether remote HTTP requests can be processed
/// </Summary>
Public bool isreusable
{
Get {return true ;}
}

/// <Summary>
/// Send the verification code image to the Web browser
/// </Summary>
/// <Param name = "context"> </param>
Public void processrequest (httpcontext context)
{
Int size = authcode. mysize; // int32.parse (string) Context. session ["size"]);
Memorystream MS = new memorystream (); // creates a memory stream (the initial length is 0 automatically expanded)
String numstr = getrandomnumberstring (size); // The Verification Code character.
Context. session. Add ("value", numstr); // Save the verification code character to the session.
Bitmap thebitmap = createimage (numstr); // obtain the verification code Image
Thebitmap. Save (MS, system. Drawing. imaging. imageformat. JPEG); // write bitmap into memory stream
Context. response. clearcontent (); // clear all content output in the buffer
Context. response. contenttype = "image/JPEG"; // you need to modify the HTTP header to output the image information.
Context. response. binarywrite (Ms. toarray (); // write the memory stream to the HTTP output stream
Thebitmap. Dispose (); // release resources
Ms. Close (); // release resources
Ms. Dispose (); // release resources
Context. response. End ();
}


}
}
 

4 --- generate the solution and class library, open the web form, and click the toolbar.

 

5 -- drag to the web form

<% @ Page Language = "C #" autoeventwireup = "true" codefile = "default. aspx. cs" inherits = "_ default" %>

<% @ Register Assembly = "authcode" namespace = "authcode" tagprefix = "PC3" %>

<〈! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en ""Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<HTML xmlns ="Http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> No title page </title>
</Head>
<Body>
<Form ID = "form1" runat = "server">
<Div>
<C0: authcode id = "authcode1" runat = "server" mysize = "5"/>
</Div>
</Form>
</Body>
</Html>

Set Verification Code character Length

6 -- add a node in the webconfig File

<System. Web>
<Httphandlers>
<Add verb = "*" Path = "*. JD" type = "authcode. authcodehttphander"/>
</Httphandlers>
</System. Web>

7 -- View in the browser

Click to refresh

8 -- "this. authcode1.getvalue () to obtain the verification code

End

First write TechnologyArticleI would also like to invite you to give me more advice.

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.