故如虹,知恩;故如月,知明
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术

handler实现一个简单的验证码

3981人阅读 2019/8/14 16:06 总访问:3911974 评论:0 收藏:0 手机
分类: .NET


handler代码如下:

public class CodeHandler : IHttpHandler,IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "image/png";

            Bitmap bt = new Bitmap(100, 36);

            //通过图片拿到图片的画笔类
            Graphics gp = Graphics.FromImage(bt);

            //填充一个背景颜色
            gp.FillRectangle(new SolidBrush(Color.Black), 0, 0, 100, 36);

            //产生一个字符串
            string codestr = "";
                        //构建大写小写与数字
            List<int> codelist = new List<int>();
            for (int i = 97, j = 65; i <= 122; i++, j++)
            {
                codelist.Add(i);
                codelist.Add(j);
            }
            for (int i = 48; i <= 57; i++)
            {
                codelist.Add(i);
            }

            //随机因子,随时因子一样随机数就一样,默认随机因子是时间
            //for (int i = 0; i < 4; i++)
            //{
            //    Random random = new Random(Guid.NewGuid().GetHashCode());
            //    int code = (char)random.Next(48, 123);
            //    if (!codelist.Contains(code))
            //    {
            //        i--;
            //        continue;
            //    }
            //    codestr += (char)code;
            //}
            
            string codeStr = "";
            Random random = new Random();
            for (int i = 0; i < 4; i++)
            {
                int charindex = random.Next(0, codeList.Count);
                codeStr += (char)codeList[charindex];
            }
            graphics.DrawString(codeStr, font, solidBrush, 25, 8);

            //产生干扰下
            for (int i = 0; i < 3; i++)
            {
                gp.DrawLine(new Pen(Color.White, 1), random2.Next(0, 100), random2.Next(0, 36), random2.Next(0, 100), random2.Next(0, 36));
            }

            //产生小字干扰
            for (int i = 0; i < 10; i++)
            {
                Random random = new Random(Guid.NewGuid().GetHashCode());

                int code = (char)random.Next(48, 123);
                if (!codelist.Contains(code))
                {
                    i--;
                    continue;
                }
                char lcode = (char)code;

                gp.DrawString(lcode+"", new Font("宋体", 8), new SolidBrush(Color.White), random2.Next(0, 100), random2.Next(0, 36));
            }

            context.Session["codestr"] = codestr;

            bt.Save(context.Response.OutputStream, ImageFormat.Png);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

效果如下:



欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739

评价