新建一个一般处理程序
引用三个命名空间:
using System.Drawing;
using System.Drawing.Imaging;
using System.Web.SessionState;
继承接口:IRequiresSessionState
/一般处理程序中生成验证码:
Color[] colors = new Color[]
{
Color.Red,Color.Green,Color.Yellow,Color.Blue,Color.AliceBlue,Color.Aqua,Color.Bisque,Color.Brown
};
Image img = new Bitmap(100, 36);
Graphics graphics = Graphics.FromImage(img);
Random random = new Random(DateTime.Now.Millisecond);
int charNum1 = random.Next(97, 122);
int charNum2 = random.Next(97, 122);
int charNum3 = random.Next(97, 122);
int charNum4 = random.Next(97, 122);
//保存验证码
string validCode = string.Format("{0}{1}{2}{3}", (char)charNum1, (char)charNum2, (char)charNum3, (char)charNum4);
context.Session["sn"] = validCode;
Font font = new Font("宋体", 24);
Brush brush1 = new SolidBrush(colors[random.Next(0, colors.Length-1)]);
graphics.DrawString(((char)charNum1).ToString(), font, brush1, 7, -3);
Brush brush2 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
graphics.DrawString(((char)charNum2).ToString(), font, brush2, 26,-9);
Brush brush3 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
graphics.DrawString(((char)charNum3).ToString(), font, brush3, 50, 0);
Brush brush4 = new SolidBrush(colors[random.Next(0, colors.Length - 1)]);
graphics.DrawString(((char)charNum4).ToString(), font, brush4, 70, -7);
context.Response.ContentType = "image/jpeg";
img.Save(context.Response.OutputStream, ImageFormat.Jpeg);
img.Dispose();
在网页中添加
<img src="Handler.ashx?k=1" alt="看不清,换一张" class="pure-input-1-2" style="width: 100px; height: 36px;" onclick="this.src=this.src+1" />
注:Handler.ashx为一般处理程序名称
按以上操作完成即ok