[原创]重复获得验证码的问题

验证码的页面可能由于验证码不清楚,单击需要获得新的验证码
服务器端用C#实现如下:

/// <summary>
/// 验证码类,用于生成验证码
/// </summary>
public static class ValidateCode
{
private static string Cr&#101;ateRandomCode(int codeCount)
{
string allChar = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,W,X,Y,Z";
string[] allCharArray = allChar.Split(&#39;,&#39;);
string randomCode = "";
int temp = -1;
Random rand = new Random();
for (int i = 0; i < codeCount; i++)
{
if (temp != -1)
{
rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
}
int t = rand.Next(35);
if (temp == t)
{
return Cr&#101;ateRandomCode(codeCount);
}
temp = t;
randomCode += allCharArray&#91;t&#93;;
}
return randomCode;
}
public static MemoryStream Cr&#101;ateImage(out string checkCode)
{
//生成随机数
checkCode = Cr&#101;ateRandomCode(4);
int iwidth = (int)(checkCode.Length * 13.5);
System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
Graphics g = Graphics.FromImage(image);
Font f = new System.Drawing.Font("Arial", 12, System.Drawing.FontStyle.Bold);
Brush b = new System.Drawing.SolidBrush(Color.Black);
//g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
g.Clear(Color.White);
g.DrawString(checkCode, f, b, 3, 3);
Pen blackPen = new Pen(Color.Black, 0);
Random rand = new Random();
for (int i = 0; i < 3; i++)
{
int y = rand.Next(image.Height);
g.DrawLine(blackPen, 0, y, image.Width, y);
}
MemoryStream ms = new MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
g.Dispose();
image.Dispose();
return ms;
}
}
&#91;/code&#93;
使用Asp.net MVC实现的Controller调用验证码的Action如下:
没有生成中间gif,jpg文件
&#91;code&#93;
/// <summary>
/// 获得验证码
/// </summary>
public void GetValidateCode()
{
try
{
//生成验证码
string validateCode;
Session["ValidateCode"] = "";
//生成验证码图片
MemoryStream ms = ValidateCode.Cr&#101;ateImage(out validateCode);
ViewData["Code"] = ms;
//保存到Session
Session["ValidateCode"] = validateCode;
Response.ClearContent();
Response.ContentType = "image/Gif";
Response.BinaryWrite(ms.ToArray());
}
catch (Exception e)
{
Response.Write("验证码生成失败!错误消息:" + e.Message);
}
}

页面代码:

<script language="javascript" type="text/javascript">
//获得验证码
function GetCode()
{
//注意后面一定要加随机数,这样<img>才能更新为新的验证码
$("#validateImg").attr("src","/user/GetValidateCode?sd="+Math.random());
}
</script>
<a id="getCode" href="javascript:GetCode();"><img  id="validateImg"  src="/user/GetValidateCode"  alt="点击获得验证码" /></a>
赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏