今天开始做一个新项目,包含完整的注册登陆流程,在登陆时需要输入验证码防止暴力破解。
制作思路是这样的:
准备使用handler一般处理程序来写,先随机从0-9和A-Z里随机取4个数字,将内容保存在Session中供验证时使用。然后使用Bitmap和Graphics画图,最后以image/png类型输出流。
具体代码如下:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.SessionState;
namespace MyCms.Handler
{
/// <summary>
/// VerificationCode 的摘要说明
/// </summary>
public class VerificationCode : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
System.Random rand = new Random();
int len = 4; //rand.Next(4, 6);
char[] chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
System.Text.StringBuilder myStr = new System.Text.StringBuilder();
for (int iCount = 0; iCount < len; iCount++)
{
myStr.Append(chars[rand.Next(chars.Length)]);
}
string verificationCode = myStr.ToString();
context.Session["VerificationCode"] = verificationCode;
Size ImageSize = Size.Empty;
using (Bitmap bmp = new Bitmap(121, 40)) {
using (Graphics g = Graphics.FromImage(bmp)) {
SolidBrush brush = new SolidBrush(Color.FromArgb(79, 137, 205));
g.Clear(Color.FromArgb(197,227,240));
g.DrawString(verificationCode, new Font("MS Sans Serif", 26,FontStyle.Strikeout,GraphicsUnit.Pixel), brush, new PointF(18, 6));
}
using (System.IO.MemoryStream ms = new System.IO.MemoryStream()) {
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
context.Response.ContentType = "image/png";
ms.WriteTo(context.Response.OutputStream);
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
当然在handler中想要使用session的话还需要实现IRequiresSessionState接口,否则是无法操作Session的。
源文件下载: