<%@ WebHandler Language="C#" Class="ValidCode" %>
using System;
using System.Web;
public class ValidCode : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
string strValidCode = GetValidCode(5);
context.Session["ValidCode"] = strValidCode;
Bitmap image = new Bitmap(120, 30);
Graphics g = Graphics.FromImage(image);
try
{
Random random = new Random();
g.Clear(Color.White);
for(int i=0;i<25;i++)
{
int x1 = random.Next(image.Width);
int x2 = random.Next(image.Width);
int y1 = random.Next(image.Height);
int y2 = random.Next(image.Height);
g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
}
Font font = new System.Drawing.Font("Arial", 20, (System.Drawing.FontStyle.Bold));
LinearGradientBrush brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.DarkRed, 3, true);
g.DrawString(strValidCode, font, brush, 5, 2);
g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Heigth - 1);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, ImageFormat.Gif);
context.Response.ClearContent();
context.Response.ContentType = "image/Gif";
context.Response.BinaryWrite(ms.ToArray());
}
finally
{
g.Dispose();
image.Dispose();
}
}
private string GetValidCode(int num)
{
string strRandomCode = "ABCD1EF2GH3IJ4KL5MN6P7QR8ST9UVWXYZ";
char[] chastr = strRandomCode.ToCharArray();
StringBuilder sbValidCode = new StringBuilder();
Random rd = new Random();
for(int i=0;i<num;i++)
{
sbValidCode.Append(strRandomCode.Substring(rd.Next(0, strRandomCode.Length), 1));
}
return sbValidCode.ToString();
}
public bool IsReusable {
get {
return false;
}
}
}