c#生成驗證碼


using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;

需要特別引用:System.Drawing

        /// <summary>
        /// 生成隨機數
        /// </summary>
        /// <param name="codeLen">數據的長度</param>
        /// <returns></returns>
        public static string CreateRandomCode(int codeLen)
        {
            string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
            string[] allCharAry = allChar.Split(',');
            string randomCode = "";
            int temp = -1;
            Random rand = new Random();
            for (int i = 0; i < codeLen; i++)
            {
                if (temp != -1)
                {
                    rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
                }
                int t = rand.Next(35);
                if (temp == t)
                {
                    return CreateRandomCode(codeLen);
                }
                temp = t;
                randomCode += allCharAry[t];
            }
            return randomCode;
        }

 

       /// <summary>
       /// 根據隨機數生成圖片
       /// </summary>
       /// <param name="validateCode">圖片中的文字</param>
       /// <returns></returns>
        public byte[] CreateValidGraphic(string validateCode)
        {
            Bitmap img = new Bitmap((int)Math.Ceiling(validateCode.Length * 16.0), 27);
            Graphics g = Graphics.FromImage(img);
            try
            {
                Random random = new Random();//生成隨機數
                g.Clear(Color.White);//清空圖片背景色
                for (int i = 0; i < 25; i++)//畫圖片的干擾線
                {
                    int x1 = random.Next(img.Width);
                    int x2 = random.Next(img.Width);
                    int y1 = random.Next(img.Height);
                    int y2 = random.Next(img.Height);
                    g.DrawLine(new Pen(Color.Silver), x1, x2, y1, y2);
                }
                Font font = new Font("Arial", 13, (FontStyle.Bold | FontStyle.Italic));
                LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, img.Width, img.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 2);
                for (int i = 0; i < 100; i++)//畫圖片的前景干擾點
                {
                    int x = random.Next(img.Width);
                    int y = random.Next(img.Height);
                    img.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, img.Width - 1, img.Height - 1);//畫圖片的邊框線
                MemoryStream stream = new MemoryStream();
                img.Save(stream, ImageFormat.Jpeg);
                return stream.ToArray();//輸入圖片
            }
            catch (Exception)
            {
                throw;
            }
        }

 

在MVC項目中使用

控制器Index中的代碼

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetRandomCode()
        {
            string code = CreateRandomCode(4);
            TempData["validateCode"] = code;
            return File(CreateValidGraphic(code), "image/jpeg");
        }

視圖Index.cshtml中的代碼

@using (Html.BeginForm())
{
    <img alt="驗證碼圖片" id="imgValidateCode" title="看不清?點擊換一張" src="@Url.Action("GetRandomCode")" onclick="this.src=this.src+'?'"/>
}

 關於驗證碼的后台校驗:

當視圖模型驗證通過的之后,需要再對驗證碼進行校驗。

在MVC中template每次取出值后就會過期,但在asp.net中session中的驗證碼不會過期,可能需要手動讓驗證碼過期。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM