zoukankan      html  css  js  c++  java
  • [网络收集]ASP.NET中的验证码代码

    HTML的代码:

    1. <!--   
    2.      Document    : ASP.NET用一般处理程序生成验证码   
    3.      Created on : 2010-6-3 17:04   
    4.      Author      : lostwolf  
    5. -->  
    6. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
    7. <html>  
    8.   <head>  
    9.     <title></title>  
    10.     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
    11.     <script type="text/javascript">  
    12.          function change() {   
    13.              var imgNode = document.getElementById("vimg");   
    14.             imgNode.src = "WaterMark.ashx?t=" + (new Date()).valueOf();   // 这里加个时间的参数是为了防止浏览器缓存的问题   
    15.          }   
    16.     </script>  
    17.   </head>  
    18.   <body>  
    19.     <img src="WaterMark.ashx" id="vimg" alt="" /><input type="button" value="换一张图片" onclick="change()" />  
    20.   </body>  
    21. </html>  
    <!--     Document   : ASP.NET用一般处理程序生成验证码    Created on : 2010-6-3 17:04    Author     : lostwolf--><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <title></title>    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />    <script type="text/javascript">        function change() {            var imgNode = document.getElementById("vimg");            imgNode.src = "WaterMark.ashx?t=" + (new Date()).valueOf();  // 这里加个时间的参数是为了防止浏览器缓存的问题        }    </script>  </head>  <body>    <img src="WaterMark.ashx" id="vimg" alt="" /><input type="button" value="换一张图片" onclick="change()" />  </body></html>


    一般处理程序WaterMark.ashx的代码:

    C#代码
    1. <%@ WebHandler Language="C#" Class="WaterMark" %>   
    2.   
    3. using System;   
    4. using System.Web;   
    5. using System.Drawing;   
    6. using System.Drawing.Drawing2D;   
    7. using System.Web.SessionState;     
    8.   
    9. public class WaterMark : IHttpHandler, IRequiresSessionState  // 要使用session必须实现该接口,记得要导入System.Web.SessionState命名空间   
    10. {   
    11.   
    12.     public void ProcessRequest(HttpContext context)   
    13.      {   
    14.         string checkCode = GenCode(5);  // 产生5位随机字符   
    15.          context.Session["Code"] = checkCode; //将字符串保存到Session中,以便需要时进行验证   
    16.          System.Drawing.Bitmap image = new System.Drawing.Bitmap(70, 22);   
    17.          Graphics g = Graphics.FromImage(image);   
    18.         try  
    19.          {   
    20.             //生成随机生成器   
    21.              Random random = new Random();   
    22.   
    23.             //清空图片背景色   
    24.              g.Clear(Color.White);   
    25.   
    26.             // 画图片的背景噪音线   
    27.             int i;   
    28.             for (i = 0; i < 25; i++)   
    29.              {   
    30.                 int x1 = random.Next(image.Width);   
    31.                 int x2 = random.Next(image.Width);   
    32.                 int y1 = random.Next(image.Height);   
    33.                 int y2 = random.Next(image.Height);   
    34.                  g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);   
    35.              }   
    36.   
    37.              Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));   
    38.              System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2F, true);   
    39.              g.DrawString(checkCode, font, brush, 2, 2);   
    40.   
    41.             //画图片的前景噪音点   
    42.              g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);   
    43.              System.IO.MemoryStream ms = new System.IO.MemoryStream();   
    44.              image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);   
    45.              context.Response.ClearContent();   
    46.              context.Response.ContentType = "image/Gif";   
    47.              context.Response.BinaryWrite(ms.ToArray());   
    48.          }   
    49.         finally  
    50.          {   
    51.              g.Dispose();   
    52.              image.Dispose();   
    53.          }   
    54.      }   
    55.   
    56.     /// <summary>   
    57.     /// 产生随机字符串   
    58.     /// </summary>   
    59.     /// <param name="num">随机出几个字符</param>   
    60.     /// <returns>随机出的字符串</returns>   
    61.     private string GenCode(int num)   
    62.      {   
    63.         string str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";//"的一是在不了有和人这中大为上个国我以要他时来用们生到作地于出就分对成会可主发年动同工也能下过子说产种面而方后多定行学法所民得经十三之进着等部度家电力里如水化高自二理起小物现实加量都两体制机当使点从业本去把性好应开它合还因由其些然前外天政四日那社义事平形相全表间样与关各重新线内数正心反你明看原又么利比或但质气第向道命此变条只没结解问意建月公无系军很情者最立代想已通并提直题党程展五果料象员革位入常文总次品式活设及管特件长求老头基资边流路级少图山统接知较将组见计别她手角期根论运农指几九区强放决西被干做必战先回则任取据处队南给色光门即保治北造百规热领七海口东导器压志世金增争济阶油思术极交受联什认六共权收证改清己美再采转更单风切打白教速花带安场身车例真务具万每目至达走积示议声报斗完类八离华名确才科张信马节话米整空元况今集温传土许步群广石记需段研界拉林律叫且究观越织装影算低持音众书布复容儿须际商非验连断深难近矿千周委素技备半办青省列习响约支般史感劳便团往酸历市克何除消构府称太准精值号率族维划选标写存候毛亲快效斯院查江型眼王按格养易置派层片始却专状育厂京识适属圆包火住调满县局照参红细引听该铁价严";   
    64.         char[] chastr = str.ToCharArray();   
    65.         // string[] source ={ "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", "V", "W", "X", "Y", "Z", "#", "$", "%", "&", "@" };   
    66.         string code = "";   
    67.          Random rd = new Random();   
    68.         int i;   
    69.         for (i = 0; i < num; i++)   
    70.          {   
    71.             //code += source[rd.Next(0, source.Length)];   
    72.              code += str.Substring(rd.Next(0, str.Length), 1);   
    73.          }   
    74.         return code;   
    75.   
    76.      }   
    77.   
    78.     public bool IsReusable   
    79.      {   
    80.         get  
    81.          {   
    82.             return false;   
    83.          }   
    84.      }   
    85.   

    方法一:
    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;

    public partial class Background_Code : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    string str2 = GenerateCheckCode();
    CreateCheckCodeImage(str2);
    }
    /// <summary>
    /// 产生数
    /// </summary>
    /// <returns></returns>
    public string GenerateCheckCode()
    {
    Random temp = new Random();
    string str1 = "0123456789abcdefghijklmnopqrstuvwxyz";
    string str = "";
    for (int i = 0; i < 4; i++)
    {
    str = str + str1.Substring(temp.Next(36), 1);
    }
    Session["Val"] = str;
    return str;
    }
    /// <summary>
    /// 产生图片
    /// </summary>
    /// <param name="num">随机产生的数字字符串</param>
    public void CreateCheckCodeImage(string num)
    {
    if (num == null || num.Trim() == String.Empty)
    return;
    System.Drawing.Bitmap img = new System.Drawing.Bitmap((int)Math.Ceiling((num.Length * 12.5)), 22);
    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(img);
    try
    {
    Random ra = new Random();
    g.Clear(System.Drawing.Color.White);
    for (int j = 0; j < 2; j++)
    {
    int x1 = ra.Next(img.Width);
    int x2 = ra.Next(img.Width);
    int y1 = ra.Next(img.Height);
    int y2 = ra.Next(img.Height);
    g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Black), x1, y1, x2, y2);
    }
    System.Drawing.Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
    System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, img.Width, img.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);
    g.DrawString(num, font, brush, 2, 2);
    for (int k = 0; k < 100; k++)
    {
    int x = ra.Next(img.Width);
    int y = ra.Next(img.Height);
    img.SetPixel(x, y, System.Drawing.Color.FromArgb(ra.Next()));
    }
    //图片边缘
    g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, img.Width - 1, img.Height - 1);
    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
    Response.ClearContent();
    Response.ContentType = "image/Gif";
    Response.BinaryWrite(ms.ToArray());
    }
    finally
    {
    g.Dispose();
    img.Dispose();
    }
    }
    }

    新建一个网页 写个img标签 src=上面的路径就可以了


    方法2:
    using System;
    using System.Web;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    public partial class images_code : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    string chkCode = string.Empty;
    //颜色列表,用于验证码、噪线、噪点
    Color[] color ={ Color.Black, Color.Red, Color.Blue, Color.Green, Color.Orange,Color.Brown, Color.DarkBlue };
    //字体列表,用于验证码
    string[] font ={ "Times New Roman", "MS Mincho", "Book Antiqua", "Gungsuh","PMingLiU", "Impact" };
    //验证码的字符集,去掉了一些容易混淆的字符
    char[] character ={ '2', '3', '4', '5', '6', '8', '9', 'A', 'B', 'C', 'D', 'E','F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'R', 'S', 'T', 'W', 'X', 'Y' };
    Random rnd = new Random();
    //生成验证码字符串
    for (int i = 0; i < 4; i++)
    {
    chkCode += character[rnd.Next(character.Length)];
    }
    //保存验证码的Cookie
    HttpCookie anycookie = new HttpCookie("validateCookie");
    anycookie.Values.Add("ChkCode", chkCode);
    HttpContext.Current.Response.Cookies["validateCookie"].Values["ChkCode"] = chkCode;
    Bitmap bmp = new Bitmap(80,20);
    Graphics g = Graphics.FromImage(bmp);
    g.Clear(Color.White);
    //画噪线
    for (int i = 0; i < 3; i++)
    {
    int x1 = rnd.Next(80);
    int y1 = rnd.Next(20);
    int x2 = rnd.Next(80);
    int y2 = rnd.Next(20);
    Color clr = color[rnd.Next(color.Length)];
    g.DrawLine(new Pen(clr), x1, y1, x2, y2);
    }
    //画验证码字符串
    for (int i = 0; i < chkCode.Length; i++)
    {
    string fnt = font[rnd.Next(font.Length)];
    Font ft = new Font(fnt, 11);
    Color clr = color[rnd.Next(color.Length)];
    g.DrawString(chkCode[i].ToString(), ft, new SolidBrush(clr), (float)i * 20 + 6, (float)2);
    }
    //画噪点
    for (int i = 0; i < 50; i++)
    {
    int x = rnd.Next(bmp.Width);
    int y = rnd.Next(bmp.Height);
    Color clr = color[rnd.Next(color.Length)];
    bmp.SetPixel(x, y, clr);
    }
    //清除该页输出缓存,设置该页无缓存
    Response.Buffer = true;
    Response.ExpiresAbsolute = System.DateTime.Now.AddMilliseconds(0);
    Response.Expires = 0;
    Response.CacheControl = "no-cache";
    Response.AppendHeader("Pragma", "No-Cache");
    //将验证码图片写入内存流,并将其以"image/Png" 格式输出
    MemoryStream ms = new MemoryStream();
    try
    {
    bmp.Save(ms, ImageFormat.Png);
    Response.ClearContent();
    Response.ContentType = "image/Png";
    Response.BinaryWrite(ms.ToArray());
    }
    finally
    {
    bmp.Dispose(); //显式释放资源
    g.Dispose();
    }
    }
    }

     


  • 相关阅读:
    [转]命令行下常用网络命令解释大全
    查看计算机时间的命令行
    线程已被中止 “Thread was being aborted”
    SharePoint 2007备份还原小结
    作业
    .NET中线程同步相关的一些类
    SharePoint对于Workflow的历史信息清理的要点
    一些操作符
    for path多行变一列
    MERGE同步
  • 原文地址:https://www.cnblogs.com/lushuicongsheng/p/1897926.html
Copyright © 2011-2022 走看看