首先,在公用项目中建立一个生成图片验证码的类型ValidateCode,代码如下

1 /// <summary> 2 3 /// 生成验证码对象 4 5 /// </summary> 6 7 public class ValidateCode 8 9 { 10 11 public ValidateCode() 12 13 { 14 15 } 16 17 ///<summary> 18 19 /// 验证码的最大长度 20 21 ///</summary> 22 23 public int MaxLength 24 25 { 26 27 get { return 10; } 28 29 } 30 31 ///<summary> 32 33 /// 验证码的最小长度 34 35 ///</summary> 36 37 public int MinLength 38 39 { 40 41 get { return 1; } 42 43 } 44 45 ///<summary> 46 47 /// 生成验证码 48 49 ///</summary> 50 51 ///<param name="length">指定验证码的长度</param> 52 53 ///<returns></returns> 54 55 public string CreateValidateCode(int length) 56 57 { 58 59 int[] randMembers = new int[length]; 60 61 int[] validateNums = new int[length]; 62 63 string validateNumberStr = ""; 64 65 //生成起始序列值 66 67 int seekSeek = unchecked((int)DateTime.Now.Ticks); 68 69 Random seekRand = new Random(seekSeek); 70 71 int beginSeek = (int)seekRand.Next(0, Int32.MaxValue - length * 10000); 72 73 int[] seeks = new int[length]; 74 75 for (int i = 0; i < length; i++) 76 77 { 78 79 beginSeek += 10000; 80 81 seeks[i] = beginSeek; 82 83 } 84 85 //生成随机数字 86 87 for (int i = 0; i < length; i++) 88 89 { 90 91 Random rand = new Random(seeks[i]); 92 93 int pownum = 1 * (int)Math.Pow(10, length); 94 95 randMembers[i] = rand.Next(pownum, Int32.MaxValue); 96 97 } 98 99 //抽取随机数字 100 101 for (int i = 0; i < length; i++) 102 103 { 104 105 string numStr = randMembers[i].ToString(); 106 107 int numLength = numStr.Length; 108 109 Random rand = new Random(); 110 111 int numPosition = rand.Next(0, numLength - 1); 112 113 validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1)); 114 115 } 116 117 //生成验证码 118 119 for (int i = 0; i < length; i++) 120 121 { 122 123 validateNumberStr += validateNums[i].ToString(); 124 125 } 126 127 return validateNumberStr; 128 129 } 130 131 ///<summary> 132 133 /// 创建验证码的图片 134 135 ///</summary> 136 137 ///<param name="containsPage">要输出到的page对象</param> 138 139 ///<param name="validateNum">验证码</param> 140 141 public byte[] CreateValidateGraphic(string validateCode) 142 143 { 144 145 Bitmap image = new Bitmap((int)Math.Ceiling(validateCode.Length * 14.0), 22); 146 147 Graphics g = Graphics.FromImage(image); 148 149 try 150 151 { 152 153 //生成随机生成器 154 155 Random random = new Random(); 156 157 //清空图片背景色 158 159 g.Clear(Color.White); 160 161 //画图片的干扰线 162 163 for (int i = 0; i < 25; i++) 164 165 { 166 167 int x1 = random.Next(image.Width); 168 169 int x2 = random.Next(image.Width); 170 171 int y1 = random.Next(image.Height); 172 173 int y2 = random.Next(image.Height); 174 175 g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2); 176 177 } 178 179 Font font = new Font("Arial", 14, (FontStyle.Bold | FontStyle.Italic)); 180 181 LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), 182 183 Color.Blue, Color.DarkRed, 1.5f, true); 184 185 g.DrawString(validateCode, font, brush, 3, 2); 186 187 //画图片的前景干扰点 188 189 for (int i = 0; i < 100; i++) 190 191 { 192 193 int x = random.Next(image.Width); 194 195 int y = random.Next(image.Height); 196 197 image.SetPixel(x, y, Color.FromArgb(random.Next())); 198 199 } 200 201 //画图片的边框线 202 203 g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1); 204 205 //保存图片数据 206 207 MemoryStream stream = new MemoryStream(); 208 209 image.Save(stream, ImageFormat.Jpeg); 210 211 //输出图片流 212 213 return stream.ToArray(); 214 215 } 216 217 finally 218 219 { 220 221 g.Dispose(); 222 223 image.Dispose(); 224 225 } 226 227 } 228 229 }
然后,在当前公用的controller中添加一个返回文件类型的action,当然也可以是所有返回类型的基类ActionResult,这个方法用来返回一个图像对象

1 /// <summary> 2 3 /// 生成验证码图像对象 4 5 /// </summary> 6 7 /// <returns></returns> 8 9 public ActionResult GetValidateCode() 10 11 { 12 13 ValidateCode vCode = new ValidateCode(); 14 15 string code = vCode.CreateValidateCode(4); 16 17 Session["ValidateCode"] = code; 18 19 byte[] bytes = vCode.CreateValidateGraphic(code); 20 21 return File(bytes, @"image/jpeg"); 22 23 }
再次,需要我们写一个返回当前验证吗的方法,这是作无刷新验证码的关键
/// <summary> /// 得到当前验证码 /// </summary> /// <returns></returns> public ActionResult GetCurrentValidateCode() { return Content(Session["ValidateCode"].ToString()); }
最后,就是页面上的事了,看代码

1 <div id="ValidateCodeSpan"> 2 3 请输入验证码:@Html.TextBox("VCode") 4 5 <img id="valiCode" style="cursor: pointer;" src="/Common/GetValidateCode" alt="看不清?请点我" /> 6 7 @Html.Hidden("ValidateCode") 8 9 <script type="text/javascript"> 10 11 $(function () { 12 13 //首次加载 14 15 $("#valiCode").attr("src","/Common/GetValidateCode?time=" + (new Date()).getTime()); 16 17 $.get("/Common/GetCurrentValidateCode", function (data) { 18 19 $("#ValidateCode").val(data); 20 21 }); 22 23 //单击验证码事件 24 25 $("#valiCode").bind("click", function () { 26 27 this.src = "/Common/GetValidateCode?time=" + (new Date()).getTime(); 28 29 $.get("/Common/GetCurrentValidateCode", function (data) { 30 31 $("#ValidateCode").val(data); 32 33 }); 34 35 }); 36 37 }); 38 39 </script> 40 41 </div>