主要是相互学习一下mvc,希望各位大神指导
/// <summary>
/// 生成随机数字
/// </summary>
/// <returns>随机数字</returns>
public string GetCode(int len = )
{
string strCode = string.Empty;
char code;
int num;
Random rnd = new Random();
for (int i = ; i < len; i++)
{
num = rnd.Next();
if (num % == )
{
code = (char)('' + (char)(num % ));
}
else
{
//code = (char)('0' + (char)(num % 10));
code = (char)('A' + (char)(num % ));
}
strCode += code.ToString();
}
return strCode;
}
生成随机数
/// <summary>
/// 生成验证码(保存验证码到图片)
/// </summary>
/// <returns>二进制</returns>
public byte[] ProcessRequestImage(string validateCode)
{ HttpContext context = HttpContext.Current;
using (Bitmap bmp = new Bitmap(validateCode.Length * + , ))
{
Graphics g = Graphics.FromImage(bmp);
g.Clear(Color.White);
Random rnd = new Random();
for (int i = ; i < ; i++)
{
int x1 = rnd.Next(bmp.Width);
int y1 = rnd.Next(bmp.Height);
int x2 = rnd.Next(bmp.Width);
int y2 = rnd.Next(bmp.Height);
g.DrawLine(new Pen(Color.FromArgb(rnd.Next(), rnd.Next(), rnd.Next())), x1, y1, x2, y2);
}
g.DrawRectangle(new Pen(Color.FromArgb(rnd.Next(), rnd.Next(), rnd.Next())), new Rectangle(, , bmp.Width - , bmp.Height - ));
for (int i = ; i < ; i++)
{
bmp.SetPixel(rnd.Next(bmp.Width), rnd.Next(bmp.Height), Color.FromArgb(rnd.Next(), rnd.Next(), rnd.Next()));
}
for (int i = ; i < validateCode.Length; i++)
{
FontFamily[] familys = FontFamily.Families;
FontFamily family = familys[rnd.Next(familys.Length)];
g.DrawString(validateCode[i].ToString(), new Font(family, , FontStyle.Bold), new SolidBrush(Color.FromArgb(rnd.Next(), rnd.Next(), rnd.Next())), new PointF( + i * , ));
} //保存图片数据
MemoryStream stream = new MemoryStream();
bmp.Save(stream, ImageFormat.Jpeg); // 输出图片流
return stream.ToArray();
}
}
生成验证码图片
/// <summary>
/// 验证码
/// </summary>
/// <returns></returns>
public ActionResult VerifyCode()
{
h.Base.Public.SecurityCode seCode = new h.Base.Public.SecurityCode();
var code = seCode.GetCode();
Session["code"] = code;
var bytes = seCode.ProcessRequestImage(code);
return File(bytes, "image/jpeg");
}
控制器代码
<div class="pdiv">
<input type="image" id="valiCode" src="/Based/VerifyCode" />
</div> <script>
(function () {
//刷新验证码
var codeUrl = "/Based/VerifyCode";
$(valiCode).on("click", function () {
this.src = codeUrl + "?time=" + (new Date()).getTime();
}); })(jQuery)
</script>
view视图代码
这段代码我测试过了。。 是可以通过的。