How to use an ASP. NET implementation to generate code for the CAPTCHA feature

Source: Internet
Author: User
This article mainly introduces the implementation of the ASP. NET generated verification code function, combined with the case of the form of a more detailed analysis of the principle of ASP, steps and related implementation skills, and with the demo source for the reader to download the reference, the need for friends can refer to the next





In this paper, the Generation Verification code for ASP is described. Share to everyone for your reference, as follows:



Generate Verification Code principle: generate random characters, and the word Fuzhou into a picture, at the same time stored in the session, and then verify that the user input content and the session in accordance with the verification code.



: User can click to toggle captcha 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
{
  // The 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 validation code in the session
    CreateCodeImage (validateCode, context);
  }
  public bool IsReusable {
    get {
      return false;
    }
  }
  /// <summary>
  /// generate 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 (','); // Convert string to 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 text
    g.DrawString (checkCode, f, b, 0, 1);
    // random lines
    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 ();
  }
}


Encapsulation into 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 generates a verification code
/// </ summary>
public class ValidateNumber
{
  // The character set that generates the verification code (the 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 verification code
  /// </ summary>
  public int MaxLength
  {
    get {return 10;}
  }
  /// <summary>
  /// minimum length of verification code
  /// </ summary>
  public int MinLength
  {
    get {return 1;}
  }
  /// <summary>
  /// generate verification code
  /// </ summary>
  /// <param name = "length"> Specify the length of the verification code </ param>
  /// <returns> </ returns>
  public string CreateValidateNumber (int length)
  {
    string [] CharArray = charcode.Split (','); // Convert string to character array
    string 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>
  /// Create a picture of 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 a random generator
      Random random = new Random ();
      // Empty the background color of the picture
      g.Clear (Color.White);
      // Draw 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);
      // Draw the foreground interference point of the picture
      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 of the picture
      g.DrawRectangle (new Pen (Color.Silver), 0, 0, image.Width-1, image.Height-1);
      // Save picture data
      MemoryStream stream = new MemoryStream ();
      image.Save (stream, ImageFormat.Jpeg);
      // output image
      context.Response.Clear ();
      context.Response.ContentType = "image / jpeg";
      context.Response.BinaryWrite (stream.ToArray ());
    }
    finally
    {
      g.Dispose ();
      image.Dispose ();
    }
  }
  /// <summary>
  /// get the length of the verification code image
  /// </ summary>
  /// <param name = "validateNumLength"> Length of verification code </ param>
  /// <returns> </ returns>
  public static int GetImageWidth (int validateNumLength)
  {
    return (int) (validateNumLength * 14);
  }
  /// <summary>
  /// get the height of the captcha image
  /// </ summary>
  /// <returns> </ returns>
  public static double GetImageHeight ()
  {
    return 22;
  }
} 
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.