Draw verification code,
1. Generate a verification code string
// Randomly generate a verification code string of the specified length
Private string RandomCode (int length) {string s = "0123456789 zxcvbnmasdfghjklqwertyuiop"; StringBuilder sb = new StringBuilder (); Random rand = new Random (); int index; for (int I = 0; I <length; I ++) {index = rand. next (0, s. length); sb. append (s [index]);} return sb. toString ();}
2. Draw interference lines
private void PaintInterLine(Graphics g,int num,int width,int height){ Random r = new Random(); int startX, startY, endX, endY; for(int i = 0; i < num; i++) { startX = r.Next(0, width); startY = r.Next(0, height); endX = r.Next(0, width); endY = r.Next(0, height); g.DrawLine(new Pen(Brushes.Red), startX, startY, endX, endY); }}
3. Generate Verification Code
Public ActionResult GetValidateCode () {byte [] data = null; string code = RandomCode (5); TempData ["code"] = code; // define an artboard MemoryStream MS = new MemoryStream (); using (Bitmap map = new Bitmap (100, 40) {// paint brush, draw a drawing on the specified drawing board // g. dispose (); using (Graphics g = Graphics. fromImage (map) {g. clear (Color. white); g. drawString (code, new Font ("", 18.0F), Brushes. blue, new Point (10, 8); // draw the interference line PaintInterLine (g, 30, map. width, map. height);} map. save (MS, System. drawing. imaging. imageFormat. jpeg);} data = ms. getBuffer (); return File (data, "image/jpeg ");}
4. Obtain the verification code in the previous section.
<Form method = "post" id = "form1" action = "/ValidateCode/login"> <div class = "code"> <input type = "text" name = "code "/> <a style =" text-decoration: none; cursor: pointer "id =" chCode "> can't see clearly? For another </a> </div> <input type = "submit" value = "Logon"/> </div> </form>
5. Background Verification
Public ActionResult Login () {string code = Request. form ["code"]. toString (); if (string. isNullOrEmpty (code) {return Content ("verification cannot be empty");} if (! Code. Equals (TempData ["code"]) {return Content ("Incorrect verification input");} return Content ("correct verification input ");}