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

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

/// 验证码类,用于生成验证码
///

public static class ValidateCode
{
private static string CreateRandomCode(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(',');
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 CreateRandomCode(codeCount); } temp = t; randomCode += allCharArray[t]; } return randomCode; } public static MemoryStream CreateImage(out string checkCode) { //生成随机数 checkCode = CreateRandomCode(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; } } [/code] 使用Asp.net MVC实现的Controller调用验证码的Action如下: 没有生成中间gif,jpg文件 [code] ///

/// 获得验证码
///

public void GetValidateCode()
{
try
{
//生成验证码
string validateCode;
Session["ValidateCode"] = "";
//生成验证码图片
MemoryStream ms = ValidateCode.CreateImage(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);
}
}
[/code]
页面代码:
[code]

点击获得验证码
[/code]