C#之asp.net 及MVC 生成動態驗證碼:


C#之asp.net 及MVC 生成動態驗證碼:

 

1.生成驗證碼字符串

復制代碼
// 隨機生成指定長度的驗證碼字符串
private
string RandomCode(int length) { string s = "0123456789zxcvbnmasdfghjklqwertyuiop"; 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.繪制干擾線

復制代碼
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.生成驗證碼

復制代碼
public ActionResult GetValidateCode()
{
    byte[] data = null;
    string code = RandomCode(5);
    TempData["code"] = code;
    //定義一個畫板
    MemoryStream ms = new MemoryStream();
    using(Bitmap map=new Bitmap(100, 40))
    {
        //畫筆,在指定畫板畫板上畫圖
        //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));
            //繪制干擾線
            PaintInterLine(g, 30, map.Width, map.Height);
        }
        map.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    }
    data = ms.GetBuffer();
    return File(data, "image/jpeg");
}
復制代碼

 

4.前段獲取驗證碼

復制代碼
<form method="post" id="form1" action="/ValidateCode/login">
    <div class="code">
        <input type="text" name="code" />
        <img id="code" src="/ValidateCode/GetValidateCode/" />
        <a style="text-decoration:none; cursor:pointer" id="chCode">看不清?換一個</a>
    </div>
    <div >
        <input type="submit"  value="登錄" />
    </div>
</form>
復制代碼

 

 5.后台驗證

復制代碼
public ActionResult Login()
{
    string code = Request.Form["code"].ToString();
    if (string.IsNullOrEmpty(code))
    {
        return Content("驗證輸不能為空");
    }
    if (!code.Equals(TempData["code"]))
    {
        return Content("驗證輸不正確");
    }
    return Content("驗證輸入正確");
}
復制代碼
 


免責聲明!

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



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