Asp. NET verification Code (3 kinds) _ Practical skills

Source: Internet
Author: User

In our daily life, we will encounter the verification code when we use the website, have we ever thought about why we should use the verification code?

In fact, the role of verification code is to prevent malicious crack password, brush tickets, forum irrigation, brush page. Effectively prevent a hacker to a specific registered user with a specific program brute force to break the way to continue the logon attempt. Share with you today three kinds of asp.net authentication code.

1.gsc_webcontrollibrary This is a control found on the Internet, very easy to use. But the effect is not particularly good (see chart below).
Although easy to use, all properties can be set like controls, but availability is not high. The user cannot customize it, and it looks like the validation code doesn't work very well.

Effect:

2. Use a page to generate a picture, another page call, the verification code in the cookie, call the cookie comparison validation. The user can change the effect and the length of the verification code as he likes.

Effect as shown:

The checkcode.aspx code is as follows:

Using System;
Using System.Data;
Using System.Configuration;
Using System.Collections;
Using System.Web;
Using System.Web.Security;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.WebControls.WebParts;
Using System.Web.UI.HtmlControls;
Using System.Drawing;
Using System.Drawing.Drawing2D;

Using System.Drawing.Imaging;
    Public partial class Tools_CheckCode:System.Web.UI.Page {protected void Page_Load (object sender, EventArgs e) { This.

  Createcheckcodeimage (Generatecheckcode ());
    private String Generatecheckcode () {int number;
    char code;

    string checkcode = String.Empty;

    System.Random Random = new Random (); for (int i = 0; i < 5; i++) {number = random.

      Next ();
      if (number% 2 = 0) code = (char) (' 0 ' + (char) (number% 10));

      else Code = (char) (' A ' + (char) (number% 26); Checkcode + = code.
    ToString ();

  } Response.Cookies.Add (New HttpCookie ("Checkcode", Checkcode));  return checkcode; } private void Createcheckcodeimage (string checkcode) {if Checkcode = null | | Checkcode.trim () = = String.Empty

    ) return;
    System.Drawing.Bitmap image = new System.Drawing.Bitmap ((int) math.ceiling (Checkcode.length * 12.5)), 22;

    Graphics g = graphics.fromimage (image);

      try {//Generate a random generator Random Random = new Random ();

      Clear the picture background color g.clear (color.white); The background noise line for the picture is for (int i = 0; i < 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.greenyellow), x1, y1, x2, y2); Font font = new System.Drawing.Font ("Verdana", System.Drawing.FontStyle.Bold |
      System.Drawing.FontStyle.Italic)); 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); Picture foreground noise point for (int i = 0; i < i++) {int x = random. Next (image.
        Width); int y = random. Next (image.

        Height); Image. SetPixel (x, Y, Color.FromArgb) (random.
      Next ())); ///Draw the picture's border line G.drawrectangle (new Pen (color.red), 0, 0, image. Width-1, image.

      HEIGHT-1);
      System.IO.MemoryStream ms = new System.IO.MemoryStream (); Image.
      Save (MS, SYSTEM.DRAWING.IMAGING.IMAGEFORMAT.GIF);
      Response.clearcontent ();
      Response.ContentType = "Image/gif"; Response.BinaryWrite (Ms.
    ToArray ());
      finally {g.dispose (); Image.
    Dispose ();

 }
  }


}

Then in the page you want to use the reference:
Usecheckcode.aspx


 

3. Create a picture with a web handler. This in fact and the previous meaning is roughly the same, call the method is basically the same as 2, the difference is, its verification code is stored in session. For learning Reference.

The effect chart is as follows:

Validateimagehandler.ashx

%@ WebHandler language= "C #" class= "Validateimagehandler"%> using System;
Using System.Web;
Using System.Web.SessionState;
Using System.Drawing;
Using System.Drawing.Imaging;

Using System.Text; <summary>///Validateimagehandler Build site Verification code feature///</summary> public class Validateimagehandler:ihttphand        Ler, irequiressessionstate {int intlength = 5; Length string stridentify = "identify"; A random string stores key values to store in session the public Validateimagehandler () {}///<summary>///generate validation picture core code///&LT;/SU
    mmary>///<param name= "HC" ></param> public void ProcessRequest (HttpContext hc) {//Set output stream picture format Hc.
    
    Response.ContentType = "Image/gif";
    Bitmap B = new Bitmap (200, 60);
    Graphics g = graphics.fromimage (b);
    G.fillrectangle (New SolidBrush (Color.yellowgreen), 0, 0, 200, 60);
    Font font = new Font (FONTFAMILY.GENERICSERIF, fontstyle.bold, GraphicsUnit.Pixel);

    Random r = new Random (); Legal random display character list String strletters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
    
    StringBuilder s = new StringBuilder (); Draws randomly generated strings to the picture for (int i = 0; i < intlength i++) {s.append (strletters.substring r.next (0, Strletter
      s.length-1), 1); g.DrawString (S[s.length-1].
    ToString (), Font, New SolidBrush (Color.Blue), I *, R.next (0, 15));
    //Generate interference lines pen pen = new Pen (new SolidBrush (Color.Blue), 2); for (int i = 0; i < i++) {G.drawline (pen, New Point (R.next (0, 199), R.next (0,)), New Point (R.next 0,
    199), R.next (0, 59)); } b.save (hc.
    Response.outputstream, imageformat.gif); Hc. Session[stridentify] = s.tostring (); First save in session, verify that the user input is consistent with HC.
  
  Response.End ();
    ///<summary>///Indicates whether such instances can be shared by multiple requests (reuse can improve performance)///</summary> public bool IsReusable {get
    {return true;
 }
  }
}

Above is the Asp.net3 kind of authentication code, each has its own advantages and disadvantages, I hope you can skillfully implement the functions of different authentication code.

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.