Rumah > pembangunan bahagian belakang > Tutorial C#.Net > C#验证码的创建与使用的示例代码分享

C#验证码的创建与使用的示例代码分享

黄舟
Lepaskan: 2017-03-24 11:42:30
asal
1312 orang telah melayarinya

这篇文章主要介绍了C#验证码的创建与使用方法,结合实例形式较为详细的分析了C#验证码的创建、验证等操作步骤与相关技巧,需要的朋友可以参考下

本文实例讲述了C#验证码的创建与使用方法。分享给大家供大家参考,具体如下:

1、C#创建验证码

① 创建获取验证码页面(ValidateCode.aspx)

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>获取验证码</title>
</head>
<body>
  <form id="form1" runat="server">
    <p>获取验证码</p>
  </form>
</body>
</html>
Salin selepas log masuk

② 编写获取验证码代码(ValidateCode.aspx.cs)

/// <summary>
/// 验证码类型(0-字母数字混合,1-数字,2-字母)
/// </summary>
private string validateCodeType = "0";
/// <summary>
/// 验证码字符个数
/// </summary>
private int validateCodeCount = 4;
/// <summary>
/// 验证码的字符集,去掉了一些容易混淆的字符
/// </summary>
char[] character = { &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;, &#39;6&#39;, &#39;8&#39;, &#39;9&#39;, &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &#39;E&#39;, &#39;F&#39;, &#39;G&#39;, &#39;H&#39;, &#39;J&#39;, &#39;K&#39;, &#39;L&#39;, &#39;M&#39;, &#39;N&#39;, &#39;P&#39;, &#39;R&#39;,
 &#39;S&#39;, &#39;T&#39;, &#39;W&#39;, &#39;X&#39;, &#39;Y&#39; };
protected void Page_Load(object sender, EventArgs e)
{
  //取消缓存
  Response.BufferOutput = true;
  Response.Cache.SetExpires(DateTime.Now.AddMilliseconds(-1));
  Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
  Response.AppendHeader("Pragma", "No-Cache");
  //获取设置参数
  if (!string.IsNullOrEmpty(Request.QueryString["validateCodeType"]))
  {
    validateCodeType = Request.QueryString["validateCodeType"];
  }
  if (!string.IsNullOrEmpty(Request.QueryString["validateCodeCount"]))
  {
    int.TryParse(Request.QueryString["validateCodeCount"], out validateCodeCount);
  }
  //生成验证码
  this.CreateCheckCodeImage(GenerateCheckCode());
}
private string GenerateCheckCode()
{
  char code ;
  string checkCode = String.Empty;
  System.Random random = new Random();
  for (int i = 0; i < validateCodeCount; i++)
  {
    code = character[random.Next(character.Length)];
    // 要求全为数字或字母
    if (validateCodeType == "1")
    {
      if ((int)code < 48 || (int)code > 57)
      {
        i--;
        continue;
      }
    }
    else if (validateCodeType == "2")
    {
      if ((int)code < 65 || (int)code > 90)
      {
        i--;
        continue;
      }
    }
    checkCode += code;
  }
  Response.Cookies.Add(new System.Web.HttpCookie("CheckCode", checkCode));
  this.Session["CheckCode"] = checkCode;
  return checkCode;
}
private void CreateCheckCodeImage(string checkCode)
{
  if (checkCode == null || checkCode.Trim() == String.Empty)
    return;
  System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length*15.0+40)), 23);
  System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image);
  try
  {
    //生成随机生成器
    Random random = new Random();
    //清空图片背景色
    g.Clear(System.Drawing.Color.White);
    //画图片的背景噪音线
    for (int i = 0; i < 25; i++)
    {
      int x1 = random.Next(image.Width);
      int x2 = random.Next(image.Width);
      int y1 = random.Next(image.Height);
      int y2 = random.Next(image.Height);
      g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
    }
    System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
    System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new 
    System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);
    int cySpace = 16;
    for (int i = 0; i < validateCodeCount; i++)
    {
      g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);
    }
    //画图片的前景噪音点
    for (int i = 0; i < 100; i++)
    {
      int x = random.Next(image.Width);
      int y = random.Next(image.Height);
      image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));
    }
    //画图片的边框线
    g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    Response.ClearContent();
    Response.ContentType = "image/Gif";
    Response.BinaryWrite(ms.ToArray());
  }
  finally
  {
    g.Dispose();
    image.Dispose();
  }
}
Salin selepas log masuk

2、验证码的使用

① 验证码的前段显示代码

代码如下:

<img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" 
onclick
="this.src=&#39;/ValidateCode.aspx?ValidateCodeType=1&&#39;+Math.random();" id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
Salin selepas log masuk

② 创建验证码测试页面(ValidateTest.aspx)

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>验证码测试</title>
</head>
<body>
  <form id="form1" runat="server">
  <p>
    <input runat="server" id="txtValidate" />
    <img src="/ValidateCode.aspx?ValidateCodeType=1&0.011150883024061309" 
    onclick="this.src=&#39;/ValidateCode.aspx?ValidateCodeType=1&&#39;+Math.random();" 
    id="imgValidateCode" alt="点击刷新验证码" title="点击刷新验证码" style="cursor: pointer;">
    <asp:Button runat="server" id="btnVal" Text="提交" onclick="btnVal_Click" />
  </p>
  </form>
</body>
</html>
Salin selepas log masuk

③ 编写验证码测试的提交代码(ValidateTest.aspx.cs)

protected void btnVal_Click(object sender, EventArgs e)
{
  bool result = false;  //验证结果
  string userCode = this.txtValidate.Value; //获取用户输入的验证码
  if (String.IsNullOrEmpty(userCode))
  {
    //请输入验证码
    return;
  }
  string validCode = this.Session["CheckCode"] as String; //获取系统生成的验证码
  if (!string.IsNullOrEmpty(validCode))
  {
    if (userCode.ToLower() == validCode.ToLower())
    {
      //验证成功
      result = true;
    }
    else
    {
      //验证失败
      result = false;
    }
  }
}
Salin selepas log masuk

Atas ialah kandungan terperinci C#验证码的创建与使用的示例代码分享. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan