<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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>
<title></title>
</head>
<body>
<form runat="server">
<image src="Image.ashx" onClick="this.src='Image.ashx?aaa=aaa'"></image>
验证码:<asp:TextBox ID="TextBox1" runat="server" onClick="this.src='Image.ashx?aa='+new Date()"></asp:TextBox>
<asp:LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click">登 陆</asp:LinkButton>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
string old_code = Convert.ToString(Session["code"]);
if (old_code == TextBox1.Text)
{
Response.Write("验证成功!");
}
else {
Response.Write("验证失败1");
}
}
}
<%@ WebHandler Language="C#" Class="Image" %>
using System;
using System.Web;
//在一般应用程序中使用session要引用System.Web.SessionState.IRequiresSessionState
public class Image : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "image/JPEG";
//创建一个画布
using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(100, 30))
{
//创建一个图片格式
using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
{
/*g.DrawString("平安北京", new System.Drawing.Font("宋体", 16), System.Drawing.Brushes.Green, new System.Drawing.PointF(0, 0));
g.DrawEllipse(System.Drawing.Pens.Red, new System.Drawing.Rectangle(10, 10, 10, 10));
System.Drawing.Pen pen = (System.Drawing.Pen)System.Drawing.Pens.Red.Clone();
pen.Width = 3;
g.DrawEllipse(pen, new System.Drawing.Rectangle(20, 20, 10, 10));
bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);*/
Random rand = new Random();
int code = rand.Next(10000, 99999);
string strCode = code.ToString();
HttpContext.Current.Session["code"] = strCode;
g.DrawString(strCode, new System.Drawing.Font("宋体", 16), System.Drawing.Brushes.Green, new System.Drawing.PointF(0, 0));
g.DrawEllipse(System.Drawing.Pens.Red, new System.Drawing.Rectangle(10, 10, 10, 10));
bitmap.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
//context.Response.Write("Hello World");
}
public bool IsReusable {
get {
return false;
}
}
}