.NET MVC 使用驗證碼驗證登錄

  無圖無真像,首先截出效果圖:


  


  代碼:

<div style="margin-top: 15px;">
                    <label for="m">
                        驗證碼:</label>
                    <input name="memVerifi" style="width: 65px;" type="text" class="easyui-numberbox"
                        data-options="required:true,validType:''" />
                    <img id="imgVerifi" title="單擊我可以換一張驗證碼" src="/Login/VerificationCode" οnclick="changecode()" />
                </div>

 function changecode() {
            $('#imgVerifi').attr('src', '/Login/VerificationCode?t=' + new Date().getSeconds());
        }


邏輯啥的就不說了,直接代碼


控制器代碼:


public FileResult VerificationCode()
        {
            var vc = new FortRun.Lib.Util.VerificationCode();
            System.IO.MemoryStream ms = vc.CreateCheckCodeImage();
            byte[] bytes = ms.ToArray();
            return File(bytes, @"image/gif");
        }


VerificationCode類代碼:(注:生成圖片代碼系網上下載)

using System;
using System.Drawing;

namespace FortRun.Lib.Util
{
    public class VerificationCode
    {
        private string GenerateCheckCode()
        {
            //創建整型型變量
            int number;
            //創建字符型變量
            char code;
            //創建字符串變量並初始化爲空
            string checkCode = String.Empty;
            //創建Random對象
            Random random = new Random();
            //使用For循環生成4個數字
            for (int i = 0; i < 4; i++)
            {
                //生成一個隨機數
                number = random.Next();
                //將數字轉換成爲字符型
                code = (char)('0' + (char)(number % 10));

                checkCode += code.ToString();
            }
            //將生成的隨機數添加到Session中
            System.Web.HttpContext.Current.Session["VerificationCode"] = checkCode;
            //返回字符串
            return checkCode;
        }

        public System.IO.MemoryStream CreateCheckCodeImage()
        {
            string checkCode = GenerateCheckCode();
            //判斷字符串不等於空和null
            if (checkCode == null || checkCode.Trim() == String.Empty)
            {
                System.Web.HttpContext.Current.Session["VerificationCode"] = null;
                return null;
            }

            //創建一個位圖對象
            System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 12.5)), 22);
            //創建Graphics對象
            Graphics g = Graphics.FromImage(image);

            try
            {
                //生成隨機生成器
                Random random = new Random();

                //清空圖片背景色
                g.Clear(Color.White);

                //畫圖片的背景噪音線
                for (int i = 0; i < 2; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);

                    g.DrawLine(new Pen(Color.Black), x1, y1, x2, y2);
                }

                Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
                var brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height),
                                                                     Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(checkCode, font, brush, 2, 2);

                //畫圖片的前景噪音點
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);

                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }

                //畫圖片的邊框線
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

                //將圖片輸出到頁面上
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
                return ms;
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
    }
}

驗證端代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FortRun.Model;

namespace FortRun.BLL
{
    public class LoginHelper
    {
        private string UserName { get; set; }
        private string UserPwd { get; set; }
        private string VerifiCode { get; set; }

        public LoginHelper(string username, string userpwd)
        {
            UserName = username;
            UserPwd = FortRun.Lib.Util.MD5.MD5Encrypt(userpwd, 32);
        }

        public LoginHelper(string username, string userpwd, string verificode)
        {
            UserName = username;
            UserPwd = FortRun.Lib.Util.MD5.MD5Encrypt(userpwd, 32);
            VerifiCode = verificode;
        }

        public bool CheckLogin(ref string msg)
        {
            if (!string.IsNullOrEmpty(VerifiCode))
            {
                var verificode = System.Web.HttpContext.Current.Session["VerificationCode"] as string;
                if (verificode != VerifiCode)
                {
                    msg = "驗證碼不匹配";
                    return false;
                }
            }

            if (msg == null) throw new ArgumentNullException("msg");
            //do some check
            msg = "B1AC38B1-AA8E-4187-AB94-67CA809DE505";

            if (UserName != "fortrun-001")
            {
                msg = "用戶名錯誤";
                return false;
            }
            if (UserName == "fortrun-001" && FortRun.Lib.Util.MD5.MD5Encrypt("fortrun-pwd", 32) != UserPwd)
            {
                msg = "密碼不匹配";
                return false;
            }

            var m = new M_Member
                        {
                            memCellPhone = "15888888888",
                            memID = "10001",
                            memIdNum = "362422xxxxxxxx8111",
                            memName = "xxx",
                            memRegisterTime = DateTime.Now.ToString("yyyy-MM-dd"),
                            memSex = "xxxx",
                            memStatus = "OK"
                        };

            System.Web.HttpContext.Current.Session["UserInfo"] = m;

            return true;
        }       
    }
}


很簡單,可能有新手需要吧,我以前只知道從網上索取,從未爲網上寫過點什麼。現在自己懂一點就寫一點吧。


以上代碼測試過

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章