C#验证码

2019/7/24 3:44:39 人评论 次浏览 分类:学习教程

原文链接:http://www.cnblogs.com/cyj-2012/archive/2012/10/30/2746090.html

IT小白、很少发帖。

验证码,很实用普及的功能。今天留下此贴,一来主要是给自己留下笔记,二来也可给同样是新手的童鞋学习!

好吧。不太监、代码才是王道!

 

<先贴上一效果图:>

 

共有两个页面:Login.aspx    and ValiDateCode.aspx .

 

Login.aspx:

前台代码:

 

js代码:    

<script type="text/javascript">
  //刷新验证码
  function ChangeCode() {
    var date = new Date();
    var myImg = document.getElementById("imgCode");
    var GUID = document.getElementById("lblGUID");

    if (GUID != null) {
      if (GUID.innerHTML != "" && GUID.innerHTML != null) {
      myImg.src = "ValiDateCode.aspx?GUID=" + GUID.innerHTML + "&flag=" + date.getMilliseconds();
    }
  }
  return false;
}
</script>

 

HTML:  (样式自己调、只贴主要代码)

验证码:
<asp:TextBox ID="txtCode" runat="server" Width="80px"></asp:TextBox>
<a id="aCode" href="#" οnclick="ChangeCode();return false;">
  <asp:Image ID="imgCode" runat="server" ImageUrl="~/ValiDateCode.aspx?GUID=GUID" ImageAlign="AbsMiddle"  ToolTip="看不清,换一个" />
</a>
<asp:Label ID="lblGUID" runat="server" Style="display: none"></asp:Label>
<asp:Label ID="Label1" runat="server" BackColor="Transparent" ForeColor="Red"></asp:Label>
<asp:Button ID="Button1" Text="提交" runat="server" OnClick="btnLogin_Click" />

 

后台代码:

protected void Page_Load(object sender, EventArgs e)
{
  //生成GUID标识符用与刷新验证码时作为参数值
  this.ViewState["GUID"] = System.Guid.NewGuid().ToString();
  this.lblGUID.Text = this.ViewState["GUID"].ToString();
}
//验证输入的验证码
protected void btnLogin_Click(object sender, EventArgs e)
{
  string txtCode = this.txtCode.Text.ToString().Trim().ToUpper();//一定记得把所输入的验证码转换成大写
  string SessionCode = Session["CheckCode"].ToString();
  if (txtCode != SessionCode)
  {
    this.lblMsg.Text = "验证码输入错误。";
  }
  else {
    this.lblMsg.Text = "";
  }
}

 

-------接下来才是重点_ 生成验证码 ---------

ValiDateCode.aspx

后台代码:

添加引用:
using System.Drawing;

 

protected void Page_Load(object sender, EventArgs e)
{
  string checkCode = GetRandomCode(4);  // 4----代表了验证码的个数
  Session["CheckCode"] = checkCode;
  SetPageNoCache();
  CreateImage(checkCode);
}
/// <summary>
/// 设置页面不被缓存
/// </summary>
private void SetPageNoCache()
{
  Response.Buffer = true;
  Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
  Response.Expires = 0;
  Response.CacheControl = "no-cache";
  Response.AppendHeader("Pragma", "No-Cache");
}


/// <summary>
/// 生成验证码
/// </summary>
/// <param name="CodeCount">验证码个数</param>
/// <returns>个数为CodeCount的验证码</returns>
private string GetRandomCode(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,M,N,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(temp * i * ((int)DateTime.Now.Ticks));
    }

    int t = rand.Next(33);

    while (temp == t)
    {
      t = rand.Next(33);
    }

    temp = t;
    RandomCode += allCharArray[t];
  }

  return RandomCode;
}

/// <summary>
/// 创建验证码背景色以及文字颜色(红色代表数字,黑色代表字母)
/// </summary>
/// <param name="checkCode">验证码</param>
private void CreateImage(string checkCode)
{
  int iwidth = (int)(checkCode.Length * 14);
  System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 20);
  Graphics g = Graphics.FromImage(image);
  Font f = new System.Drawing.Font("Arial ", 10);//, System.Drawing.FontStyle.Bold);
  Brush b = new System.Drawing.SolidBrush(Color.Black);
  Brush r = new System.Drawing.SolidBrush(Color.FromArgb(166, 8, 8));

  //g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
  //g.Clear(Color.AliceBlue);//背景色
  g.Clear(System.Drawing.ColorTranslator.FromHtml("#99C1CB"));//背景色

  char[] ch = checkCode.ToCharArray();
  for (int i = 0; i < ch.Length; i++)
  {
    if (ch[i] >= '0' && ch[i] <= '9')
    {
      //数字用红色显示
      g.DrawString(ch[i].ToString(), f, r, 3 + (i * 12), 3);
    }
    else
    { //字母用黑色显示
      g.DrawString(ch[i].ToString(), f, b, 3 + (i * 12), 3);
    }
  }

  //for循环用来生成一些随机的水平线
  //Pen blackPen = new Pen(Color.Black, 0);
  //Random rand = new Random();
  //for (int i = 0; i < 5; i++)
  //{
  // int y = rand.Next(image.Height);
  // g.DrawLine(blackPen, 0, y, image.Width, y);
  //}

  System.IO.MemoryStream ms = new System.IO.MemoryStream();
  image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
  //history back 不重复
  Response.Cache.SetNoStore();//这一句
  Response.ClearContent();
  Response.ContentType = "image/Jpeg";
  Response.BinaryWrite(ms.ToArray());
  g.Dispose();
  image.Dispose();
}

 

 

 

over!

 

 

 

 



转载于:https://www.cnblogs.com/cyj-2012/archive/2012/10/30/2746090.html

相关资讯

    暂无相关的资讯...

共有访客发表了评论 网友评论

验证码: 看不清楚?
    -->