To write a verification code in WebForm, you must first build a generic handler.
public class Handler:ihttphandler, irequiressessionstate//session interface {public void ProcessRequest (HttpContext cont EXT) {context. Response.ContentType = "Image/jpeg"; String charSet = "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"; string[] Chararray = Charset.split (', '); String code = ""; int temp =-1; Random rand1 = new Random (); for (int j = 0; J < 4; J + +) {if (temp! =-1) {rand1 = new Random (J * Temp * ((int) DateTime.Now.Ticks)); } int t = Rand1. Next (chararray.length-1); if (temp = = t) {return; } temp = t; Code + = Chararray[t]; } context. session["Yanzhen"]=code; System.Drawing.Bitmap image = New System.Drawing.Bitmap (50, 23); Graphics g = graphics.fromimage (image); Font f = new System.Drawing.Font ("Arial", A, (System.Drawing.FontStyle.Italic | System.Drawing.FontStyle.Bold)); Front color Brush b = new System.Drawing.SolidBrush (color.black); Background color g.clear (color.white); Fill text g.drawstring (code, 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); }//RandomPoint for (int i = 0; i <; 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.BinaryWrite (Ms. ToArray ()); }
Then refresh with a simple Ajax asynchronous operation
function Ajax (url,success) {
var xmlrequest = window. XMLHttpRequest? New XMLHttpRequest (): New ActiveXObject (' microsoft.xmlhttp ');
Xmlrequest.open ("POST", url, True);
Xmlrequest.onreadystatechange () = function () {
if (xmlrequest.readystate==4) {
if (Xmlrequest.status = = 200) {
Success (Xmlrequest.responsetext);
}
else {
Alert ("Action Error! ");
}
}
}
Xmlrequest.send ();
}
WebForm Verification Code