MVC系列学习(十五)-验证码

1.方式一:

public class VCode

{

    /// <summary>

    /// 生成验证码图片 字节数组

    /// </summary>

    /// <returns></returns>

    public byte[] GetVCode()

    {

        using (Image img = new Bitmap(90, 30))

        {

            string strCode = GetRandomStr();

            HttpContext.Current.Session["vcode"] = strCode;

            using (Graphics g = Graphics.FromImage(img))

            {

                g.Clear(Color.White);

                g.DrawRectangle(Pens.Blue, 0, 0, img.Width - 1, img.Height - 1);

                DrawPoint(g);

                g.DrawString(strCode, new Font("微软雅黑", 15), Brushes.Blue, new PointF(5, 2));

                DrawPoint(g);

                using (System.IO.MemoryStream ms = new MemoryStream())

                {

                    //将图片 保存到内存流中

                    img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

                    //将内存流 里的 数据  转成 byte 数组 返回

                    return ms.ToArray();

                }

            }

        }

        return null;

    }





    Random random = new Random();

    /// <summary>

    /// 生成随机数

    /// </summary>

    /// <returns></returns>

    string GetRandomStr()

    {

        string str = string.Empty;

        string[] strArr = { "", "N", "B", "", "", "", "", "", "", "", "S", "B", "", "", "" ,"",""};

        for (int i = 0; i < 4; i++)

        {

            int index = random.Next(strArr.Length);

            str += strArr[index];

        }

        return str;

    }

    /// <summary>

    /// 画线段

    /// </summary>

    /// <param name="g"></param>

    void DrawPoint(Graphics g)

    {

        Pen[] pens = { Pens.Blue, Pens.Black, Pens.Red, Pens.Green };

        Point p1;

        Point p2;

        int length = 1;

        for (int i = 0; i < 50; i++)

        {

            p1 = new Point(random.Next(79), random.Next(29));

            p2 = new Point(p1.X - length, p1.Y - length);

            length = random.Next(5);

            g.DrawLine(pens[random.Next(pens.Length)], p1, p2);

        }

    }

}

调用:

image

方式二:

使用一般处理程序

ValidateCode.ashx下载

调用

image

3.得出结论

原来mvc中也是可以用一般处理程序的,因为mvc与webform用的是同一天asp.net框架。当请求到达请求管道的时候,在第七个事件中,看请求有没有实现mvchandler接口,如果没有就跳过第七个事件,进入第八个事件,在第8个事件中,创建一般处理程序对象,然后在第11和12事件之间,调用对象的PR()方法

你可能感兴趣的:(mvc)