Using HttpHandler to realize asp.net verification code function __.net

Source: Internet
Author: User
use HttpHandler to implement ASP.net authentication code features

Because of the current registration machine, post machine, such as garbage software is too much, in order to effectively intercept this information, many sites need to use the verification code, the following HttpHandler to implement the verification code mechanism/* ********************************   * author:          1987raymond   * team:            juice sharing   * created time:    2009-3-10 19:22:46  * CopyRight:        Juice Sharing  Team Copyright   All rights reserved   * namespace:        Juice.Common.HttpHandlers  * class/interface:  validatecoderender  * ***********************************************/    using System;   using system.text;  using system.web;  using system.drawing;  using  system.drawing.imaging;  using system.web.sessionstate;    namespace  juice.common.httphandlers  {  &NBsp;   /// <summary>      ///  Verification Code generator        /// </summary>      public sealed class  validatecoderender : ihttphandler, irequiressessionstate      {          /// <summary>           ///  Constructors           /// </summary>           public validatecoderender ()            { }             #region   Private fields             /// <summary>           ///  Verification Code length            /// </summary>          private int m_codelength = 5 ;            /// <summary>           ///  save values in session state           ///  </summary>          private string m_ sessionname =  "Validatecode";            ///  <summary>          ///  Image's width            /// </summary>           private int m_imagewidth = 160;             /// <summary>          ///  Image Long            /// </summary>          private  int m_ImageHeight = 60;            ///  <summary>          ///  image background color            /// </summary>           private color m_backgroundcolor = color.fromargb (212, 236, 189);            /// <summary>           ///  color of the verification code on the image           /// </ summary>          private color m_codecolor =  color.fromargb (132, 199, 1);            ///  <summary&Color of gt;          ///  jamming graphics            /// </summary>          private  color m_obstructioncolor = color.gray;             /// <summary>          ///  strings used to generate random authentication codes           /// </summary>           private const string m_CodeString =  " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 me and your size ";              #endregion              #region   ihttphandler  members             /// <summary>          ///  can reuse           /// </summary>           public bool IsReusable           {               get { return true; }          }            /// <summary>           ///  Processing Requests           /// </summary>           /// <param name= "Context" ></param>           public void processrequest (HttpContext  Context)           {               ///format of output                context. response.contenttype =  "Image/gif";               random random = new random ();               ///is used to hold randomly obtained strings                stringbuilder s = new stringbuilder ();               ///Create drawing images                using  (Bitmap bitmap = new bitmap (this.m_ imagewidth, this.m_imageheight))                {                  / Create a drawing surface with this object to draw the various symbols, etc.To the developed image                    using  (Graphics graphics = graphics.fromimage (bitmap))                    {                       ///Generate background color                         graphics. FillRectangle (New solidbrush (this.m_backgroundcolor), &NBSP;0,&NBSP;0,&NBSP;THIS.M_IMAGEWIDTH,&NBSP;THIS.M _imageheight);                          #region   Build Verification code            Font   &NBSP;&NBSP;&NBSP;&NB for             ///authentication codesp;                using  (Font font = new font (fontfamily.genericserif, 32, fontstyle.bold |  Fontstyle.italic, graphicsunit.pixel))                        {                           for   (int i = 0; i < this.m_codelength; i++)                             {                               s.append ( ValidateCodeRender.m_CodeString.SubstrING (random. Next (0, m_codestring.length - 1),  1);                                ///draws characters to the image                                graphics. DrawString (s[s.length - 1]. ToString (),  font, new solidbrush (This.m_codecolor),  i * 32, random. Next (0, 24));                             }                       }                        #endregion                           #region   Plotting jamming graphics and noise                          //Interference Drawing Brushes                        using  (Pen pen = new pen New solidbrush (this.m_ Obstructioncolor),  1)                        {                           for  (int i  = 0; i < 10; i++)                            {                                graphics. DrawLine (Pen, new point) (random. Next (0, this.m_imagewidth - 1),  random. Next (0, this.m_imageheight - 1)),  new point (random. Next (0, this.m_imagewidth - 1),  random. Next (0, this.m_imageheight - 1));                             }                        }                       for  (INT&NBSP;I&NBSP;=&NBSP;0;&NBSP;I&NBSP;&LT;&NBSP;100;&Nbsp;i++)                        {                             bitmap. SetPixel (random. Next (This.m_imagewidth),  random. Next (This.m_imageheight),  color.fromargb (random. Next ());                       }                            #endregion                          ///save image to output stream                        bitmap. Save (context. Response.outpUtstream, imageformat.gif);                   }              }              ///saves the value of the CAPTCHA to the user session state, and is case-insensitive               context. Session[this.m_sessionname] = s.tostring (). ToLower ();              context. Response.End ();          }              #endregion       } } 

The above class is the class that draws the captcha image and outputs it to the page, which implements the IHttpHandler interface

Next, add this item to the

Juice.common.httphandlers.validatecoderender,juice.common according to your own situation.

The following is called on a specific page:

Test verification Code: <a                        href= "Javascript:refreshcode ();" > Refresh Verification Code </a>  <script language= "JavaScript"  type= "Text/javascript" >                   function  Refreshcode ()                    {                   Var e=gid ("Validatecode");                   e.src= "/validatecode.aspx" + "? t=" +new date () totimestring ();                   }  &NBsp;               </script>  

The effect is shown in the following illustration:

Attention this place:///saves the value of the CAPTCHA to the user session state, and does not distinguish between the case context. Session[this.m_sessionname] = s.tostring (). ToLower ();

I'm saving the captcha in session, so if you need to check if a user's input is correct, just look at the value and the value in the session.


At the same time, it's a little bit of a note that I saw some of the values in the online tutorials stored in the cookie, which I thought was wrong and lost the ability to verify the code because the cookie was also accessible to the client.

You can also expand the contents of the verification code, such as the conversion of arithmetic and so on form

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.