Example of the code generation function implemented by ASP. NET [demo source code], asp. netdemo

Source: Internet
Author: User

Example of the code generation function implemented by ASP. NET [demo source code], asp. netdemo

This example describes the function of generating verification codes implemented by ASP. NET. We will share this with you for your reference. The details are as follows:

Verification Code Generation Principle: generate a random character, generate the character into an image, and store it in the Session. Then, verify that the content entered by the user matches the verification code in the Session.

: You can click to switch the verification code information.

General handler: CheckCodeHandler. cs

<% @ WebHandler Language = "C #" Class = "CheckCodeHandler" %> using System; using System. web; using System. text; using System. drawing; using System. web. sessionState; public class CheckCodeHandler: IHttpHandler, IRequiresSessionState {// character set that generates the verification code public string charcode = "2, 3, 4, 5, 6, 8, 9, A, B, C, D, E, f, G, H, J, K, M, N, P, R, S, U, W, X, Y, a, B, c, d, e, f, g, h, j, k, m, n, p, r, s, u, w, x, y "; public void ProcessRequest (HttpContext context) {String validateCode = CreateRandomCode (4); context. session ["ValidateCode"] = validateCode; // Save the verification code to CreateCodeImage (validateCode, context);} public bool IsReusable {get {return false ;}} /// <summary> /// generate the verification code /// </summary> /// <param name = "n"> Number of verification codes </param> /// <returns> Verification code string </returns> public string CreateRandomCode (int n) {string [] CharArray = charcode. split (','); // converts a string to a character array String randomCode = ""; int temp =-1; Random rand = new Random (); for (int I = 0; I <n; I ++) {if (temp! =-1) {rand = new Random (I * temp * (int) DateTime. now. ticks);} int t = rand. next (CharArray. length-1); if (temp! =-1 & temp = t) {return CreateRandomCode (n);} temp = t; randomCode + = CharArray [t];} return randomCode ;} public void CreateCodeImage (string checkCode, HttpContext context) {int iwidth = (int) (checkCode. length * 13); System. drawing. bitmap image = new System. drawing. bitmap (iwidth, 20); Graphics g = Graphics. fromImage (image); Font f = new System. drawing. font ("Arial", 12, (System. drawing. fontStyle. italic | System. drawing. fontStyle. bold); // foreground color: Brush B = new System. drawing. solidBrush (Color. black); // background color g. clear (Color. white); // fill in the Text g. drawString (checkCode, f, B, 0, 1); // random line Pen linePen = new Pen (Color. gray, 0); Random rand = new Random (); for (int I = 0; I <5; I ++) {int x1 = rand. next (image. width); int y1 = rand. next (image. height); int x2 = rand. next (image. width); int y2 = rand. next (image. height); g. drawLine (linePen, x1, y1, x2, y2);} // random point for (int I = 0; I <30; I ++) {int x = rand. next (image. width); int y = rand. next (image. height); image. setPixel (x, y, Color. gray);} // border g. drawRectangle (new Pen (Color. gray), 0, 0, image. width-1, image. height-1); // output image System. IO. memoryStream MS = new System. IO. memoryStream (); image. save (MS, System. drawing. imaging. imageFormat. jpeg); context. response. clearContent (); context. response. contentType = "image/jpeg"; context. response. binaryWrite (ms. toArray (); g. dispose (); image. dispose ();}}

Encapsulated as a Class Library: ValidateNumber. cs

Using System; using System. collections. generic; using System. linq; using System. web; using System. drawing; using System. web. UI; using System. drawing. drawing2D; using System. IO; using System. drawing. imaging; /// <summary> /// ValidateNumber: generate the verification code. /// </summary> public class ValidateNumber {// character set that generates the verification code (confusing characters are removed) private string charcode = "2, 3, 4, 5, 6, 8, 9, A, B, C, D, E, F, G, H, J, K, M, N, P, r, S, U, W, X, Y, a, B, c, d, e, f, g, h, j, k, m, N, p, r, s, u, w, x, y "; /// <summary> /// Maximum length of the Verification Code /// </summary> public int MaxLength {get {return 10 ;}} /// <summary> /// minimum length of the Verification Code /// </summary> public int MinLength {get {return 1 ;}} /// <summary> /// generate the verification code /// </summary> /// <param name = "length"> specify the verification code length </param> /// <returns> </returns> public string CreateValidateNumber (int length) {string [] CharArray = charcode. split (','); // converts a string to the character array st Ring randomCode = ""; int temp =-1; Random rand = new Random (); for (int I = 0; I <length; I ++) {if (temp! =-1) {rand = new Random (I * temp * (int) DateTime. now. ticks);} int t = rand. next (CharArray. length-1); if (temp! =-1 & temp = t) {return CreateValidateNumber (length);} temp = t; randomCode + = CharArray [t];} return randomCode ;} /// <summary> /// the image for creating the verification code /// </summary> /// <param name = "context"> context object </param> /// <param name = "validateNum"> Verification Code </param> public void CreateValidateGraphic (HttpContext context, string validateNum) {int iwidth = (int) (validateNum. length * 14); Bitmap image = new Bitmap (iwidth, 22); Graphics g = Graphics. fromImage (image); try {// generate Random generator random Random = new Random (); // clear the image background color g. clear (Color. white); // The interference line of the picture. for (int 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 Font ("Arial", 12, (FontStyle. bold | FontStyle. italic); LinearGradientBrush brush = new LinearGradientBrush (new Rectangle (0, 0, image. width, image. height), Color. blue, Color. darkRed, 1.2f, true); g. drawString (validateNum, font, brush, 3, 2); // foreground disturbance of the image to be painted for (int I = 0; I <100; I ++) {int x = random. next (image. width); int y = random. next (image. height); image. setPixel (x, y, Color. fromArgb (random. next ();} // draw the border line g of the image. drawRectangle (new Pen (Color. silver), 0, 0, image. width-1, image. height-1); // Save the image data. MemoryStream = new MemoryStream (); image. save (stream, ImageFormat. jpeg); // output the image context. response. clear (); context. response. contentType = "image/jpeg"; context. response. binaryWrite (stream. toArray ();} finally {g. dispose (); image. dispose ();}} /// <summary> /// obtain the length of the Verification Code image /// </summary> /// <param name = "validateNumLength"> Verification code length </param>/ // <returns> </returns> public static int GetImageWidth (int validateNumLength) {return (int) (validateNumLength * 14 );} /// <summary> /// obtain the height of the Verification Code image /// </summary> /// <returns> </returns> public static double GetImageHeight () {return 22 ;}}

Appendix:Click here for the complete instance codeDownload from this site.

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.