剑轩

handler实现一个简单的验证码

电脑版发表于:2019/8/14 16:06


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;
            }
        }
    }

效果如下:



关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢