YZM.ashx.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Web; namespace WebApplication1 { /// <summary> /// YZM 的摘要说明 /// </summary> public class YZM : IHttpHandler, System.Web.SessionState.IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/JPEG"; using (System.Drawing.Bitmap bitmap = new Bitmap(100, 50)) { using (Graphics graphics = Graphics.FromImage(bitmap)) { Random random = new Random(); int code = random.Next(1000, 9999); string strCode = Convert.ToString(code); //将验证码添加到Session中 HttpContext.Current.Session["Code"] = strCode; Font font = new Font("宋体", 20); graphics.DrawString(strCode, font, Brushes.Green, new System.Drawing.PointF(0, 0)); for (int i = 0; i < 5; i++) { graphics.DrawRectangle(Pens.BlueViolet, 0+i *5, 0+ i*8, 32, 8); graphics.DrawRectangle(Pens.BlueViolet, 0 + i*5, 0 + i*8, 32, 8); } bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg); } } } public bool IsReusable { get { return false; } } } }
验证码测试.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="验证码测试.aspx.cs" Inherits="WebApplication1.验证码测试" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <img src="YZM.ashx" onclick="src='YZM.ashx?aaa='+ new Date()"/> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" /> </div> </form> </body> </html>
验证码测试.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication1 { public partial class 验证码测试 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string strCode = Convert.ToString(Session["Code"]); if (strCode == TextBox1.Text) { Response.Write("验证码正确"); } else { Response.Write("验证码错误"); } } } }