Simple verification code control

Source: Internet
Author: User

Not very beautiful, but used to study its principles;

Is to create a new ashx file (general processing program, because I am still learning ......)


Add a call to the form in the ASPX page;


Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. Web;
Using system. drawing;
Using system. Drawing. imaging;
Using system. Web. sessionstate;

Namespace webapp
/// <Summary>
/// Summary of the Verification Code instance
/// </Summary>
Public class verification code instance: ihttphandler, irequiressessionstate // This interface must be implemented when session is used in a general processing program, in system. Web. sessionstate;

Public void processrequest (httpcontext context)
Context. response. contenttype = "image/JPEG"; // The JPG type is returned;
Using (Bitmap bitmap = new Bitmap (140, 80) // pixel size;
Using (Graphics G = graphics. fromimage (Bitmap) // generate a canvas

Random Rand = new random ();
Int code = Rand. Next (1000,999 999); // specify a random function to limit the random string size;
String strcode = code. tostring ();
Httpcontext. Current. session ["code"] = strcode; // use the session interface in a general handler;
G. Clear (color. yellowgreen); // specifies the background color;
G. drawstring (strcode, new font ("", 20), brushes. white, new pointf (15, 25); // Image Parameters, (font, size), color, and position;
Bitmap. Save (context. response. outputstream, imageformat. JPEG); // output to the stream and save it as JPG;

Public bool isreusable
Return false;


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: 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.