欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net MVC 在Controller控制器中实现验证码输出

程序员文章站 2022-04-29 13:41:29
asp.net mvc项目使用到验证码,为了让以前的WebForm代码能利用上代码经过稍微的改动即可使用代码如下: 最后别忘了session的获取设置,需要在Global.asax.cs文件中新增如下代码: html页面代码: function reloadImage(url) { document ......

   asp.net mvc项目使用到验证码,为了让以前的webform代码能利用上代码经过稍微的改动即可使用代码如下:

using system;
using system.collections.generic;
using system.web;
using system.web.mvc;
using system.web.ui;
using system.web.ui.webcontrols;
using system.drawing;

namespace angel.web.controllers
{
    public class checkcodecontroller : controller
    {
        //
        // get: /checkcode/

        public actionresult index()
        {
            this.createcheckcodeimage(generatecheckcode());
            return view();
        }

        private string generatecheckcode()
        {
            int number;
            char code;
            string checkcode = string.empty;

            system.random random = new random();
            for (int i = 0; i < 5; i++)
            {
                number = random.next();

                if (number % 2 == 0)
                    code = (char)('0' + (char)(number % 10));
                else
                    code = (char)('a' + (char)(number % 26));

                if (code == '0' || code == 'o' || code == 'l' || code == 'i')
                {
                    i = i - 1;
                }
                else
                {
                    checkcode += code.tostring();
                }
            }

            //	response.cookies.add(new httpcookie("checkcode", checkcode));
            session.contents["checkcode"] = checkcode;

            return checkcode;
        }

        private void createcheckcodeimage(string checkcode)
        {
            if (checkcode == null || checkcode.trim() == string.empty)
                return;

            system.drawing.bitmap image = new system.drawing.bitmap((int)math.ceiling((checkcode.length * 12.5)), 22);
            graphics g = graphics.fromimage(image);

            try
            {
                //生成随机生成器
                random random = new random();

                //清空图片背景色
                g.clear(color.white);

                //画图片的背景噪音线
                for (int i = 0; i < 25; i++)
                {
                    int x1 = random.next(image.width);
                    int x2 = random.next(image.width);
                    int y1 = random.next(image.height);
                    int y2 = random.next(image.height);

                    g.drawline(new pen(color.silver), x1, y1, x2, y2);
                }

                font font = new system.drawing.font("arial", 12, (system.drawing.fontstyle.bold | system.drawing.fontstyle.italic));
                system.drawing.drawing2d.lineargradientbrush brush = new system.drawing.drawing2d.lineargradientbrush(new rectangle(0, 0, image.width, image.height), color.blue, color.darkred, 1.2f, true);
                g.drawstring(checkcode, font, brush, 2, 2);

                //画图片的前景噪音点
                for (int i = 0; i < 100; i++)
                {
                    int x = random.next(image.width);
                    int y = random.next(image.height);

                    image.setpixel(x, y, color.fromargb(random.next()));
                }

                //画图片的边框线
                g.drawrectangle(new pen(color.silver), 0, 0, image.width - 1, image.height - 1);

                system.io.memorystream ms = new system.io.memorystream();
                image.save(ms, system.drawing.imaging.imageformat.gif);
                response.clearcontent();
                response.contenttype = "image/gif";
                response.binarywrite(ms.toarray());
            }
            finally
            {
                g.dispose();
                image.dispose();
            }
        }

    }
}

  最后别忘了session的获取设置,需要在global.asax.cs文件中新增如下代码:

        /// <summary>
        /// mvc为了获取session参数
        /// </summary>
        public override void init()
        {
            postauthenticaterequest += (s, e) => httpcontext.current.setsessionstatebehavior(sessionstatebehavior.required);
            base.init();
        }

        void mvcapplication_postauthenticaterequest(object sender, eventargs e)
        {
            httpcontext.current.setsessionstatebehavior(sessionstatebehavior.required);
        }

 

 

html页面代码:

views 
html代码
<img name="img1" id="img1" style="position:absolute;top:5px;right:36px!important;z-index:1000;" alt="单击图片刷新验证码" src="checkcode/index" 
onclick="javasccript:reloadimage('checkcode/index');" />
<script type="text/javascript">

function reloadimage(url) {
document.getelementbyid("img1").src = url + '?abc=' + math.random();
}

   </script>