asp.net 验证码

</pre>添加一个名为VerifyCode的aspx页面,复制粘贴以下代码就行了。<pre>
using System;
using System.Drawing;
using System.Drawing.Imaging;

/// <summary> 
/// 页面验证码程序 
/// 使用:在页面中加入HTML代码 <img src="VerifyCode.aspx"> 
/// </summary> 
public partial class VerifyCode_VerifyCode : System.Web.UI.Page
{
    static string[] FontItems = new string[] { "Arial", "Helvetica", "Geneva", "sans-serif", "Verdana" };
    static Brush[] BrushItems = new Brush[] { Brushes.OliveDrab, Brushes.ForestGreen, Brushes.DarkCyan, 
        Brushes.LightSlateGray, Brushes.RoyalBlue, Brushes.SlateBlue, Brushes.DarkViolet, Brushes.MediumVioletRed, 
        Brushes.IndianRed, Brushes.Firebrick, Brushes.Chocolate, Brushes.Peru, Brushes.Goldenrod };
    static string[] BrushName = new string[] { 
        "OliveDrab", 
        "ForestGreen", 
        "DarkCyan", 
        "LightSlateGray", 
        "RoyalBlue", 
        "SlateBlue", 
        "DarkViolet", 
        "MediumVioletRed", 
        "IndianRed", 
        "Firebrick", 
        "Chocolate", 
        "Peru", 
        "Goldenrod" };
    private static Color BackColor = Color.White;
    private static Pen BorderColor = Pens.DarkGray;
    private static int Width = 52;//52
    private static int Height = 21;//21
    private Random _random;
    private string _code;
    private int _brushNameIndex;
    override protected void OnInit(EventArgs e)
    {
        // 
        // CODEGEN: This call is required by the ASP.NET Web Form Designer. 
        // 
        //InitializeComponent(); 
        //base.OnInit(e); 
    }
    /**/
    /**/
    /**/
    /// <summary> 
    /// Required method for Designer support - do not modify 
    /// the contents of this method with the code editor. 
    /// </summary> 
    private void InitializeComponent()
    {
        //this.Load += new System.EventHandler(this.Page_Load); 
    }
    /**/
    /// <summary> 
    /// 
    /// </summary> 
    /// <param name="sender"></param> 
    /// <param name="e"></param> 
    public void Page_Load(object sender, System.EventArgs e)
    {
        if (!IsPostBack)
        {
            // 
            // TODO : initialize 
            // 
            this._random = new Random();
            this._code = GetRandomCode();
            // 
            // TODO : use Session["code"] save the VerifyCode 
            // 
            Session["code"] = this._code;
            // 
            // TODO : output Image 
            // 
            this.SetPageNoCache();
            this.OnPaint();
        }
    }
    /**/
    /**/
    /**/
    /// <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> 
    /// 取得一个 4 位的随机码 
    /// </summary> 
    /// <returns></returns> 
    private string GetRandomCode()
    {
        return Guid.NewGuid().ToString().Substring(0, 4);
    }
    /**/
    /**/
    /**/
    /// <summary> 
    /// 随机取一个字体 
    /// </summary> 
    /// <returns></returns> 
    private Font GetFont()
    {
        var fontIndex = _random.Next(0, FontItems.Length);
        var fontStyle = GetFontStyle(_random.Next(0, 2));
        return new Font(FontItems[fontIndex], 12, fontStyle);
    }
    /**/
    /**/
    /**/
    /// <summary> 
    /// 取一个字体的样式 
    /// </summary> 
    /// <param name="index"></param> 
    /// <returns></returns> 
    private FontStyle GetFontStyle(int index)
    {
        switch (index)
        {
            case 0:
                return FontStyle.Bold;
            case 1:
                return FontStyle.Italic;
            default:
                return FontStyle.Regular;
        }
    }
    /**/
    /**/
    /**/
    /// <summary> 
    /// 随机取一个笔刷 
    /// </summary> 
    /// <returns></returns> 
    private Brush GetBrush()
    {
        var brushIndex = _random.Next(0, BrushItems.Length);
        _brushNameIndex = brushIndex;
        return BrushItems[brushIndex];
    }
    /**/
    /**/
    /**/
    /// <summary> 
    /// 绘画事件 
    /// </summary> 
    private void OnPaint()
    {
        Bitmap objBitmap = null;
        Graphics g = null;
        try
        {
            objBitmap = new Bitmap(Width, Height);
            g = Graphics.FromImage(objBitmap);
            Paint_Background(g);
            Paint_Text(g);
            Paint_TextStain(objBitmap);
            Paint_Border(g);
            objBitmap.Save(Response.OutputStream, ImageFormat.Gif);
            Response.ContentType = "image/gif";
        }
        catch { }
        finally
        {
            if (null != objBitmap)
                objBitmap.Dispose();
            if (null != g)
                g.Dispose();
        }
    }
    /**/
    /**/
    /**/
    /// <summary> 
    /// 绘画背景颜色 
    /// </summary> 
    /// <param name="g"></param> 
    private void Paint_Background(Graphics g)
    {
        g.Clear(BackColor);
    }
    /**/
    /**/
    /**/
    /// <summary> 
    /// 绘画边框 
    /// </summary> 
    /// <param name="g"></param> 
    private void Paint_Border(Graphics g)
    {
        g.DrawRectangle(BorderColor, 0, 0, Width - 1, Height - 1);
    }
    /**/
    /**/
    /**/
    /// <summary> 
    /// 绘画文字 
    /// </summary> 
    /// <param name="g"></param> 
    private void Paint_Text(Graphics g)
    {
        g.DrawString(_code, GetFont(), GetBrush(), 3, 1);
    }
    /**/
    /**/
    /**/
    /// <summary> 
    /// 绘画文字噪音点 
    /// </summary> 
    /// <param name="g"></param> 
    private void Paint_TextStain(Bitmap b)
    {
        for (var n = 0; n < 30; n++)
        {
            var x = _random.Next(Width);
            var y = _random.Next(Height);
            b.SetPixel(x, y, Color.FromName(BrushName[_brushNameIndex]));
        }
    }
}


 

                
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!感谢您的提问。关于 C# ASP.NET 验证码的生成和验证,可以使用以下代码。 生成验证码: ```csharp // 生成验证码 string CheckCode = string.Empty; Random random = new Random(); for (int i = 0; i < 4; i++) { int number = random.Next(); char code = (char)('0' + (char)(number % 10)); CheckCode += code.ToString(); } // 将验证码存储到 Session 中 Session["CheckCode"] = CheckCode; // 生成验证码图片 System.Drawing.Bitmap image = new System.Drawing.Bitmap((int)Math.Ceiling((CheckCode.Length * 15.5)), 22); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image); try { // 清空图片背景色 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); } // 画图片的前景噪音点 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())); } // 画图片的验证码 System.Drawing.Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold)); 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); g.DrawString(CheckCode, font, brush, 2, 2); // 画图片的边框线 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.Jpeg); Response.ClearContent(); Response.ContentType = "image/Jpeg"; Response.BinaryWrite(ms.ToArray()); } finally { // 释放资源 g.Dispose(); image.Dispose(); } ``` 验证验证码: ```csharp // 获取用户输入的验证码 string userCode = txtCheckCode.Text.Trim(); // 获取 Session 中保存的验证码 string checkCode = Session["CheckCode"].ToString(); // 验证验证码 if (string.Compare(userCode, checkCode, true) == 0) { // 验证码输入正确 } else { // 验证码输入错误 } ``` 以上代码可以生成包含随机验证码的图片,并将图片输出到页面。在页面中添加一个图片控件即可显示验证码图片。同时,将验证码存储到 Session 中,以便在验证时使用。在用户输入验证码后,将用户输入的验证码和 Session 中保存的验证码进行比较,以验证验证码是否输入正确。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值