ASP.NET中动态生成验证码的一则方法

来源:互联网 发布:淘宝怎样买百度云资源 编辑:程序博客网 时间:2024/05/09 11:18

现在不少网站中都使用了验证码的技术,实现方式也是多种多样,这里主要介绍ASP.NET中可以采用的一种动态生成验证码的方法,可能并不十分完美,但实现难度是属于较低的。

该方法是利用了普通的动态图片生成技术,但比较特别的一点是图片的生成是在一个Page类型的子类的Page_Load方法中执行的。所以Response的ContentType为image/Gif,而非text/html。

GraphicalText.aspx.cs代码:

复制代码
using System;using System.Drawing;using System.Drawing.Imaging; namespace WebApplication1{    public partial class GraphicalText : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            using (Bitmap image = new Bitmap(30, 20))            {                using (Graphics g = Graphics.FromImage(image))                {                    g.FillRectangle(Brushes.Yellow, 0, 0, 30, 20);                    g.DrawRectangle(Pens.Red, 0, 0, 29, 19);                    Font f = new Font("Arial", 9, FontStyle.Italic);                    string code = Request.QueryString["code"];                    g.DrawString(code, f, Brushes.Blue, 0, 0);                    Response.ContentType = "image/Gif";                    image.Save(Response.OutputStream, ImageFormat.Gif);                }            }        }    }}
复制代码

注意,必须要加上这句代码——“Response.ContentType = “image/Gif”;”,否则在IE之外的浏览器中无法正确显示。

对应的GraphicalText.aspx代码很简单,只有一行,因为不需要有HTML的输出:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GraphicalText.aspx.cs" Inherits="WebApplication1.GraphicalText" %>

在主页面中关键要将图片的ImageUrl赋值为之前的页面地址,并且为了令图片内容发生变化,将4位随机数字作为它的参数。

Default.aspx.cs代码:

复制代码
using System;using System.Text; namespace WebApplication1{    public partial class _Default : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {            StringBuilder sb = new StringBuilder("~/GraphicalText.aspx?code=");            Random d = new Random();            sb.Append((char)d.Next(48, 58));            sb.Append((char)d.Next(48, 58));            sb.Append((char)d.Next(48, 58));            sb.Append((char)d.Next(48, 58));            Image1.ImageUrl = sb.ToString();        }    }}
复制代码

最后在页面中加上必要的验证代码,所有工作就都完成了。

Default.aspx代码:

按 Ctrl+C 复制代码
按 Ctrl+C 复制代码