ASP.NETMVC验证码功能实现代码

   2015-07-22 0
核心提示:ASP.NET MVC验证码功能实现代码,需要的朋友可以参考一下

前台

复制代码 代码如下:

<img id="vcodeimg" src="/Home/VCode" width="70"
                                    height="25" />
                                 <span
                                    style="cursor: pointer; text-decoration: underline">换一张</span>

控制器
复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Utility;
using Jellal**;
namespace sjlwebsite.Controllers
{
    public class CommonController : Controller
    {
        #region 验证码
        [OutputCache(Duration = 0)]
        public ActionResult VCode()
        {
            string code = ValidateCode.CreateRandomCode(4);
            Session["vcode"] = code;
            ValidateCode.CreateImage(code);
            return View();
        }

        public string GetCode()
        {
            return Session["vcode"].ToStr();
        }
        #endregion
    }
}

验证码类

复制代码 代码如下:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace Utility
{
    ///  <summary> 
    ///  完美随机验证码  0.10 
    ///  Verion:0.10 
    ///  Description:随机生成设定验证码,并随机旋转一定角度,字体颜色不同 
    ///  </summary> 
    public class ValidateCode
    {

        ///  <summary> 
        ///  生成随机码 
        ///  </summary> 
        ///  <param  name="length">随机码个数www.52mvc.com</param> 
        ///  <returns></returns> 
        public static string CreateRandomCode(int length)
        {
            int rand;
            char code;
            string randomcode = String.Empty;
            //生成一定长度的验证码 
            System.Random random = new Random();
            for (int i = 0; i < length; i++)
            {
                rand = random.Next();
                if (rand % 3 == 0)
                {
                    code = (char)('A' + (char)(rand % 26));
                }
                else
                {
                    code = (char)('0' + (char)(rand % 10));
                }
                randomcode += code.ToString();
            }
            return randomcode;
        }
        ///  <summary> 
        ///  创建随机码图片 
        ///  </summary> 
        ///  <param  name="randomcode">随机码</param> 
        public static void CreateImage(string randomcode)
        {
            int randAngle = 45; //随机转动角度 
            int mapwidth = (int)(randomcode.Length * 23);
            Bitmap map = new Bitmap(mapwidth, 28);//创建图片背景 
            Graphics graph = Graphics.FromImage(map);
            graph.Clear(Color.AliceBlue);//清除画面,填充背景 
            graph.DrawRectangle(new Pen(Color.Black, 0), 0, 0, map.Width - 1, map.Height - 1);//画一个边框 
            //graph.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;//模式 
            Random rand = new Random();
            //背景噪点生成    www.lexue001.com
            Pen blackPen = new Pen(Color.LightGray, 0);
            for (int i = 0; i < 50; i++)
            {
                int x = rand.Next(0, map.Width);
                int y = rand.Next(0, map.Height);
                graph.DrawRectangle(blackPen, x, y, 1, 1);
            }
            //验证码旋转,防止机器识别   
            char[] chars = randomcode.ToCharArray();//拆散字符串成单字符数组 
            //文字距中 
            StringFormat format = new StringFormat(StringFormatFlags.NoClip);
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;
            //定义颜色 
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };
            //定义字体 
            string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
            for (int i = 0; i < chars.Length; i++)
            {
                int cindex = rand.Next(7);
                int findex = rand.Next(5);
                Font f = new System.Drawing.Font(font[findex], 13, System.Drawing.FontStyle.Bold);//字体样式(参数2为字体大小) 
                Brush b = new System.Drawing.SolidBrush(c[cindex]);
                Point dot = new Point(16, 16);
                //graph.DrawString(dot.X.ToString(),fontstyle,new SolidBrush(Color.Black),10,150);//测试X坐标显示间距的 
                float angle = rand.Next(-randAngle, randAngle);//转动的度数 
                graph.TranslateTransform(dot.X, dot.Y);//移动光标到指定位置 
                graph.RotateTransform(angle);
                graph.DrawString(chars.ToString(), f, b, 1, 1, format);
                //graph.DrawString(chars.ToString(),fontstyle,new SolidBrush(Color.Blue),1,1,format); 
                graph.RotateTransform(-angle);//转回去 
                graph.TranslateTransform(2, -dot.Y);//移动光标到指定位置 
            }
            //graph.DrawString(randomcode,fontstyle,new SolidBrush(Color.Blue),2,2); //标准随机码 
            //生成图片 
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            map.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ContentType = "image/gif";
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());
            graph.Dispose();
            map.Dispose();
        }

    }
}

 
标签: MVC 验证码
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • asp.net mvc多条件+分页查询解决方案
    


            
asp.net mvc多条件+分页查询解决方案
    asp.net mvc多条件+分页查询解决方案
    http://www.cnblogs.com/nickppa/p/3232535.html开发环境vs2010css:bootstrapjs:jquery    bootstrap paginator原先只是想做个mvc的分页,但是一般的数据展现都需要检索条件,而且是多个条件,所以就变成了MVC多条件+分页查询因为美工不是很好,所以用的是
    02-09
  • 教程一:用ASP.NET MVC创建一个TaskList应用程序
    教程一:用ASP.NET MVC创建一个TaskList应用程
    原文地址:http://www.asp.net/learn/mvc/tutorial-01-cs.aspx本篇教程目的是让你了解创建一个ASP.NET程序是“怎么样子的”。在这篇教程里,我会从头到尾快速地创建一整个ASP.NETMVC程序。我会告诉你如何创建一个简单的TaskList程序。如果你跟ASP或者APS.NET
    02-09
  • [C#]使用 AltCover 获得代码覆盖率 - E2E Test 和 Unit Test
    [C#]使用 AltCover 获得代码覆盖率 - E2E Test
    背景在 CI/CD 流程当中,测试是 CI 中很重要的部分。跟开发人员关系最大的就是单元测试,单元测试编写完成之后,我们可以使用 IDE 或者 dot cover 等工具获得单元测试对于业务代码的覆盖率。不过我们需要一个独立的 CLI 工具,这样我们才能够在 Jenkins 的 CI
  • Ruby中文乱码问题 springmvc中文乱码
    中文乱码问题解决方法为只要在文件开头加入 # -*- coding: UTF-8 -*-(EMAC写法) 或者 #coding=utf-8 就行了。源代码文件中,若包含中文编码,则需要注意两点:1. 必须在首行添加 # -*- coding: UTF-8 -*-,告诉解释器使用utf-8来解析源码。2. 必须设置编
    02-09
  • asp.net MVC 导出查询结果到Excel
    首先在View视图中有一表单form,导出按钮input class="btn export" type="button" value="导出" /,在js写入点击导出按钮的代码,如下:$(".export").click(function () {window.location.href = "/Statis/ExportExecel?data=" + $("form").serial
    02-09
  • ASP.NET MVC3 学习心得------路由机制
    9.1 理解URLURL满足的要求:l 域名易于记忆和拼写l 简短、易输入l 可以反应出站点的结构l 可破解,用户可以通过移除URL的末尾,进而达到更高层次的信息体系结构l 持久、不能变化9.2路由机制的概述ASP.NET MVC中路由机制的两种用途:l 匹配传入的请求
    02-09
  • 从零开始实现asp.net MVC4框架网站的用户登录以及权限验证模块 详细教程
    从零开始实现asp.net MVC4框架网站的用户登录以
    https://www.cnblogs.com/cjm123/p/8515226.html用户登录与权限验证是网站不可缺少的一部分功能,asp.net MVC4框架内置了用于实现该功能的类库,只需要简单搭建即可完成该功能.下面详细介绍该功能的完成方法,尾部有实例源码下载,希望可以给刚开始接触MVC的朋友
    02-09
  • ASP.NET MVC 2扩展点之Model Binder实例分析
    ASP.NET MVC 2扩展点之Model Binder实例分析
    MVC 2的Model可以是任意一个类。许多教程只讲“ADO.NET实体数据模型”Model1.edmx然后连接mssql2005以上,自动生成数据模型。这样会让初学者不能更好地理解Model与View之间的关系。这里我详细介绍一下怎样用任意一个类做Model,这样你也可以在MVC项目中使用Ac
    02-09
  • 学习 《一步步搭建自己的博客》 第一版 之异常
    这篇博客主要是为了细说异常 , 来解读博主是如何处理异常的    上篇地址 :http://www.cnblogs.com/izhiniao/p/4776999.html首先我们从 博主的封装开始 :那么如何快速 找到这些呢 , 既然是异常 ,那么肯定是错误 , 那么就是 MvcApplication 中的 Appl
    02-09
  • asp.net mvc cooike 购物车 如何实现
    先上代码:1. ShoppingCartService 类using System;using System.Collections.Generic;using System.Linq;using LinFx;using LinFx.Data;using LinFx.Security;using LinFx.Web;using YLSPay.Data.Entity;namespace YLSPay.Data.Service{public class Shoppin
    02-09
点击排行