在MVC.NET中,我们可以用如下的方法生成验证码:
public static class VCodeHelper
{
public static int FontSize = 12;
public static int Height = 22;
public static string CreateValidateCode(int length)
{
var result = new StringBuilder();
var seekSeed = unchecked((int) DateTime.Now.Ticks);
var rand = new Random(seekSeed);
for (var i = 0; i < length; i++)
{
var c = rand.Next() % 10;
result.Append(c.ToString());
}
return result.ToString();
}
public static byte[] CreateValidateImage(string validateCode)
{
var img = new Bitmap(validateCode.Length * FontSize, Height);
var g = Graphics.FromImage(img);
var random = new Random();
try
{
g.Clear(Color.White);
for (var i = 0; i < 25; i++)
{
var x1 = random.Next(img.Width);
var x2 = random.Next(img.Width);
var y1 = random.Next(img.Height);
var y2 = random.Next(img.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
var font = new Font("Arial", FontSize, FontStyle.Bold | FontStyle.Italic);
var 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);
var x = random.Next(img.Width);
for (var i = 0; i < 100; i++)
{
var 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);
var stream = new MemoryStream();
img.Save(stream, ImageFormat.Jpeg);
return stream.ToArray();
}
finally
{
g.Dispose();
img.Dispose();
}
}
}
使用的时候,可以在Controller.cs中,添加Action,用来设置将生成的验证码存入Session,并输出验证码图片
[AllowAnonymous]
public ActionResult GetValidateCode()
{
ValidateCode vCode = new ValidateCode();
string code = vCode.CreateValidateCode(4);
Session["ValidateCode"] = code;
byte[] bytes = vCode.CreateValidateGraphic(code);
return File(bytes, @"image/jpeg");
}
在View中,加入img标签
<img id="valiCode" style="cursor: pointer;" class="col-md-2 control-label" src="~/Account/GetValidateCode" alt="验证码" />
并定义JS函数,在点击时重新生成验证码
<script type="text/javascript">
$(function () {
$("#valiCode").bind("click", function () {
this.src = "../Account/GetValidateCode";
});
});
</script>