ASP. NET MVC Captcha function implementation code


The front desk

<img id="vcodeimg" src="/Home/VCode" width="70"
                                    height="25" />
                                &nbsp;<span
                                    style="cursor: pointer; text-decoration: underline"> in 1 zhang </span>

The controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Utility;
using Jellal**;
namespace sjlwebsite.Controllers
{
    public class CommonController : Controller
    {
        #region  Verification code
        [OutputCache(Duration = 0)]
        public ActionResult VCode()
        {
            string code = ValidateCode.CreateRandomCode(4);
            Session["vcode"] = code;
            ValidateCode.CreateImage(code);
            return View();
        }
        public string GetCode()
        {
            return Session["vcode"].ToStr();
        }
        #endregion
    }
}

Verification code class

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace Utility
{
    ///  <summary> 
    ///   Perfect random captcha   0.10 
    ///  Verion:0.10 
    ///  Description: Randomly generate the set captcha and rotate it randomly 1 Fixed Angle, different font color  
    ///  </summary> 
    public class ValidateCode
    {

        ///  <summary> 
        ///   Generate random code  
        ///  </summary> 
        ///  <param  name="length"> Number of random codes www.52mvc.com</param> 
        ///  <returns></returns> 
        public static string CreateRandomCode(int length)
        {
            int rand;
            char code;
            string randomcode = String.Empty;
            // generate 1 A specified length captcha  
            System.Random random = new Random();
            for (int i = 0; i < length; i++)
            {
                rand = random.Next();
                if (rand % 3 == 0)
                {
                    code = (char)('A' + (char)(rand % 26));
                }
                else
                {
                    code = (char)('0' + (char)(rand % 10));
                }
                randomcode += code.ToString();
            }
            return randomcode;
        }
        ///  <summary> 
        ///   Create random code images  
        ///  </summary> 
        ///  <param  name="randomcode"> Random code </param> 
        public static void CreateImage(string randomcode)
        {
            int randAngle = 45; // Random rotation Angle  
            int mapwidth = (int)(randomcode.Length * 23);
            Bitmap map = new Bitmap(mapwidth, 28);// Create image background  
            Graphics graph = Graphics.FromImage(map);
            graph.Clear(Color.AliceBlue);// Clear the screen and fill the background  
            graph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, map.Width - 1, map.Height - 1);// draw 1 A border  
            //graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;// model  
            Random rand = new Random();
            // Background noise generation     www.ofstack.com
            Pen blackPen = new Pen(Color.LightGray, 0);
            for (int i = 0; i < 50; i++)
            {
                int x = rand.Next(0, map.Width);
                int y = rand.Next(0, map.Height);
                graph.DrawRectangle(blackPen, x, y, 1, 1);
            }
            // Captcha is rotated to prevent machine recognition    
            char[] chars = randomcode.ToCharArray();// Break the string into a single character array  
            // In the words from  
            StringFormat format = new StringFormat(StringFormatFlags.NoClip);
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;
            // Define the color  
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
            // Define the font  
            string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", " Song typeface " };
            for (int i = 0; i < chars.Length; i++)
            {
                int cindex = rand.Next(7);
                int findex = rand.Next(5);
                Font f = new System.Drawing.Font(font[findex], 13, System.Drawing.FontStyle.Bold);// Font style ( parameter 2 Is the font size ) 
                Brush b = new System.Drawing.SolidBrush(c[cindex]);
                Point dot = new Point(16, 16);
                //graph.DrawString(dot.X.ToString(),fontstyle,new SolidBrush(Color.Black),10,150);// test X Coordinates show spacing  
                float angle = rand.Next(-randAngle, randAngle);// Degree of rotation  
                graph.TranslateTransform(dot.X, dot.Y);// Move the cursor to the specified location  
                graph.RotateTransform(angle);
                graph.DrawString(chars.ToString(), f, b, 1, 1, format);
                //graph.DrawString(chars.ToString(),fontstyle,new SolidBrush(Color.Blue),1,1,format); 
                graph.RotateTransform(-angle);// Turn back  
                graph.TranslateTransform(2, -dot.Y);// Move the cursor to the specified location  
            }
            //graph.DrawString(randomcode,fontstyle,new SolidBrush(Color.Blue),2,2); // Standard random code  
            // Generate images  
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            map.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ContentType = "image/gif";
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            graph.Dispose();
            map.Dispose();
        }
    }
}