ASP.NET中如何动态生成验证码2014-08-19现在不少网站中都使用了验证码的技术,实现方式也是多种多样,这里主要介绍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();}}}