文章来源:http://blog.csdn.net/wipeouter/article/details/6927734
一、验证码描述类
- using System;
- /// <summary>
- /// 验证码描述
- /// </summary>
- public class ValidateImage
- {
- public Guid Key { get; set; }
- public string Value { get; set; }
- }
二、生成验证码图片
- #region 验证码
- /// <summary>
- /// 用于前台调用,key为调用网址生成
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public ActionResult ValidateImgShow(Guid key)
- {
- ViewData["Key"] = key;
- return View();
- }
- /// <summary>
- /// 用于生成验证码图片
- /// </summary>
- /// <param name="key"></param>
- public void ValidateImg(Guid key)
- {
- Response.ContentEncoding = System.Text.Encoding.UTF8;
- Bitmap imgOutput = new Bitmap(100, 24, PixelFormat.Format24bppRgb);
- Graphics g = System.Drawing.Graphics.FromImage(imgOutput);
- g.Clear(Color.Green);
- g.SmoothingMode = SmoothingMode.AntiAlias;
- //为了支持每个用户不同页显示不同的验证码,session里存储一个ValidateImage序列,每列对应一个key和value
- List<ValidateImage> sessions;
- ValidateImage img = new ValidateImage()
- {
- Key = key,
- Value = getCode()
- };
- if (Session["validateCode"] == null)
- {
- sessions = new List<ValidateImage>();
- sessions.Add(img);
- }
- else
- {
- sessions = (List<ValidateImage>)Session["validateCode"];
- bool isExist = false;
- for (int i = 0; i < sessions.Count; i++)
- {
- //如果已经存在此key的验证码seesion,则修改
- if (sessions[i].Key == key)
- {
- isExist = true;
- sessions[i] = img;
- }
- }
- if (!isExist)
- {
- //每个用户同时最多支持30个验证码
- if (sessions.Count > 30)
- {
- sessions.RemoveAt(0);//删除第一个
- }
- sessions.Add(img);
- }
- }
- Session["validateCode"] = sessions;
- string tmpData = img.Value;
- g.DrawString(tmpData, new Font("黑体", 13, FontStyle.Bold), new SolidBrush(Color.White), new PointF(10, 1));
- g.FillRectangle(new LinearGradientBrush(new Point(0, 0), new Point(99, 21), Color.FromArgb(0, 0, 0, 0), Color.FromArgb(215, 215, 215, 215)), 0, 0, 99, 21);
- imgOutput.Save(Response.OutputStream, ImageFormat.Jpeg);
- g.Dispose();
- imgOutput.Dispose();
- Response.End();
- }
- /// <summary>
- /// 随机生成验证码
- /// </summary>
- /// <returns></returns>
- private string getCode()
- {
- string vchar = "1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
- string[] vcarray = vchar.Split(new char[] { ',' });
- string vnum = "";
- int iSeed = 4;
- Random ra = new Random();
- for (byte i = 1; i < 5; i++)
- {
- iSeed = ra.Next(0, 32);
- vnum += vcarray[iSeed];
- }
- return vnum;
- }
- #endregion
三、获取当前页对应验证码的值
- /// <summary>
- /// 获取某页(以key为区别)当前图片验证码,如超时,为null
- /// </summary>
- /// <returns></returns>
- public static string GetValidateCode(HttpContextBase context, Guid codeKey)
- {
- if (context.Session["validateCode"] == null)
- return null;
- //return Bzh.DataConvert.getStringFromObject(context.Session["validateCode"]);
- List<ValidateImage> imgs = (List<ValidateImage>)context.Session["validateCode"];
- string code = "";
- for (int i = 0; i < imgs.Count; i++)
- {
- if (imgs[i].Key == codeKey)
- code = imgs[i].Value;
- }
- return code;
- }
四、客户端显示验证码
- <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>无标题页</title>
- <% Guid key = (Guid)ViewData["Key"]; %>
- <%Response.Write("<script>var _key='" + key.ToString() + "';</script>"); %>
- <script>
- function refresh_() {
- var d = new Date();
- document.getElementById("dimg").src = "/Home/Validateimg?key=" + _key + "&d=" + d.getTime().toString();
- }
- </script>
- </head>
- <body style="padding: 0; margin: 0;">
- <a href="#" onclick="refresh_();return false;">
- <img src="/Home/Validateimg?key=<%=key.ToString() %>" id="dimg" alt="点击重新加载" style="border: 0;" /></a>
- </body>
- </html>
五、从iframe调用显示
- <td>
- <%
- Guid valImgKey = Guid.NewGuid();
- Response.Write("<script>var _key='" + valImgKey.ToString() + "';</script>");
- %>
- <iframe src="/Home/ValidateImgShow?key=<%=valImgKey.ToString() %>" style="width: 120px; height: 24px; overflow: hidden"
- scrolling="no" frameborder="0"></iframe>
- </td>
对于获取验证码的那段,可以用Linq简化代码:
- /// <summary>
- /// 获取某页(以key为区别)当前图片验证码,如超时,为null
- /// </summary>
- /// <returns></returns>
- public static string GetValidateCode(HttpContextBase context, Guid codeKey)
- {
- if (context.Session["validateCode"] == null)
- return null;
- List<ValidateImage> imgs = (List<ValidateImage>)context.Session["validateCode"];
- string code = "";
- var query = from t in imgs where t.Key == codeKey select t.Value;
- foreach (string v in query)
- {
- code = v;
- }
- return code;
- }