現在不少網站中都使用了驗證碼的技術,實現方式也是多種多樣,這裡主要介紹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();
}
}
}
查看本欄目