本帖最后由 黑马-杨鹏立 于 2013-3-9 22:50 编辑
好久没写验证码功能了,今天又从写了一下,忘记得差不多了。。。当作笔记以后方便查阅和大家分享下。。。。
ashx通过GDI话验证码
namespace Web.CLAdmin
{
/// <summary>
/// authCode 的摘要说明
/// </summary>
public class authCode : IHttpHandler, IRequiresSessionState(需要实现他)
{
/// <summary>
/// 通过IhttpHandler实现图片验证码
/// </summary>
/// <param name="context"></param>
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/gif";
//建立BitMap对象,绘图
Bitmap baseMap = new Bitmap(44, 20);
Graphics graph = Graphics.FromImage(baseMap);
graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 44, 20);
Font font = new Font(FontFamily.GenericSerif, 12, FontStyle.Bold, GraphicsUnit.Pixel);
Random rd = new Random();
string letters = "ABCDEFGHIJKLMNPQRSTUVWXYZ";
string letter;
StringBuilder sb = new StringBuilder();
//添加随机的4个字母
for (int i = 0; i < 4; i++)
{
letter = letters.Substring(rd.Next(0, letters.Length - 1), 1);
sb.Append(letter);
graph.DrawString(letter, font, new SolidBrush(Color.Black), i * 10, rd.Next(0, 5));
}
//混淆背景 Pen linePen = new Pen(new SolidBrush(Color.Black), 1);
for (int x = 0; x < 3; x++)
graph.DrawLine(linePen, new Point(rd.Next(0, 43), rd.Next(0, 19)), new Point(rd.Next(0, 43), rd.Next(0, 19)));
//将图片保存到输出流中
baseMap.Save(context.Response.OutputStream, ImageFormat.Gif);
context.Session["CheckCode"] = sb.ToString(); //如果没有实现IRequiresSessionState,则这里会出错,也无法生成图片,做session为了取得验证码信息
context.Response.End();
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
前台调用
<script type="text/javascript">
function change() {
var imgNode = document.getElementById("safecode");
imgNode.src = "authCode.ashx?t=" + (new Date()).valueOf(); // "authCode.ashx?t=" + (new Date()).valueOf(); 这句话可以改变验证码,这里加个时间的参数是为了防止浏览器缓存的问题
}
</script>
<img src="authCode.ashx" id="safecode"/>
|