C#之asp.net 及MVC 生成动态验证码:

C#之asp.net 及MVC 生成动态验证码:

1.生成验证码字符串

C#之asp.net 及MVC 生成动态验证码:
// 随机生成指定长度的验证码字符串
private string RandomCode(int length)
{
string s = "0123456789zxcvbnmasdfghjklqwertyuiop";
StringBuilder sb = new StringBuilder();
Random rand = new Random();
int index;
for(int i = ; i < length; i++)
{
index = rand.Next(, s.Length);
sb.Append(s[index]);
}
return sb.ToString();
}
C#之asp.net 及MVC 生成动态验证码:

2.绘制干扰线

C#之asp.net 及MVC 生成动态验证码:
private void PaintInterLine(Graphics g,int num,int width,int height)
{
Random r = new Random();
int startX, startY, endX, endY;
for(int i = ; i < num; i++)
{
startX = r.Next(, width);
startY = r.Next(, height);
endX = r.Next(, width);
endY = r.Next(, height);
g.DrawLine(new Pen(Brushes.Red), startX, startY, endX, endY);
}
}
C#之asp.net 及MVC 生成动态验证码:

3.生成验证码

C#之asp.net 及MVC 生成动态验证码:
public ActionResult GetValidateCode()
{
byte[] data = null;
string code = RandomCode();
TempData["code"] = code;
//定义一个画板
MemoryStream ms = new MemoryStream();
using(Bitmap map=new Bitmap(, ))
{
//画笔,在指定画板画板上画图
//g.Dispose();
using (Graphics g = Graphics.FromImage(map))
{
g.Clear(Color.White);
g.DrawString(code,new Font("黑体",18.0F),Brushes.Blue,new Point(,));
//绘制干扰线
PaintInterLine(g, , map.Width, map.Height);
}
map.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
}
data = ms.GetBuffer();
return File(data, "image/jpeg");
}
C#之asp.net 及MVC 生成动态验证码:

4.前段获取验证码

C#之asp.net 及MVC 生成动态验证码:
<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>
C#之asp.net 及MVC 生成动态验证码:

5.后台验证

C#之asp.net 及MVC 生成动态验证码:
public ActionResult Login()
{
string code = Request.Form["code"].ToString();
if (string.IsNullOrEmpty(code))
{
return Content("验证输不能为空");
}
if (!code.Equals(TempData["code"]))
{
return Content("验证输不正确");
}
return Content("验证输入正确");
}
C#之asp.net 及MVC 生成动态验证码:
 
上一篇:【poj 3090】Visible Lattice Points(数论--欧拉函数 找规律求前缀和)


下一篇:Django之动态验证码的生成