分享好友 编程语言首页 频道列表

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

VC/MFC  2015-07-22 11:140

前台

复制代码 代码如下:

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

    }
}

查看更多关于【VC/MFC】的文章

展开全文
相关推荐
反对 0
举报 0
评论 0
图文资讯
热门推荐
优选好物
更多热点专题
更多推荐文章
Ruby中文乱码问题 springmvc中文乱码
中文乱码问题解决方法为只要在文件开头加入 # -*- coding: UTF-8 -*-(EMAC写法) 或者 #coding=utf-8 就行了。源代码文件中,若包含中文编码,则需要注意两点:1. 必须在首行添加 # -*- coding: UTF-8 -*-,告诉解释器使用utf-8来解析源码。2. 必须设置编

0评论2023-02-09738

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

0评论2023-02-09334

ASP.NET MVC3 学习心得------路由机制
9.1 理解URLURL满足的要求:l 域名易于记忆和拼写l 简短、易输入l 可以反应出站点的结构l 可破解,用户可以通过移除URL的末尾,进而达到更高层次的信息体系结构l 持久、不能变化9.2路由机制的概述ASP.NET MVC中路由机制的两种用途:l 匹配传入的请求

0评论2023-02-09607

学习 《一步步搭建自己的博客》 第一版 之异常 边理解边记录 七天学会ASP.NET MVC 
这篇博客主要是为了细说异常 , 来解读博主是如何处理异常的    上篇地址 :http://www.cnblogs.com/izhiniao/p/4776999.html首先我们从 博主的封装开始 :那么如何快速 找到这些呢 , 既然是异常 ,那么肯定是错误 , 那么就是 MvcApplication 中的 Appl

0评论2023-02-09418

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

0评论2023-02-09985

ASP.NET MVC3 技术(五) JSON 数据的传递
今天微软发布了 ASP.NET MVC 3正式版,ASP.NET MVC 3 中的大多数知识点本站已经做过说明。ASP.NET MVC 3 中默认支持对 JSON 数据的接收,今天就让我们看看 JSON 数据的绑定。使用时会用到一点 jQuery 的知识,相信对经常访问本站的朋友来说并不难理解。ASP.NE

0评论2023-02-09725

ASP.NET MVC 简介
1、 ASP.NET MVC 是什么?ASP.NET MVC是微软官方提供的以MVC模式为基础的ASP.NET Web应用程序(Web Application)框架,它由Castle的MonoRail而来,日前最新版本是ASP.NET MVC 4.0。是将一个Web应用分解为:Model、View和Controller。ASP.NET MVC框架提供了一个可

0评论2023-02-09559

asp.net mvc 最简单身份验证 [Authorize]通过的标准
[Authorize]public ContentResult Index2(){return Content("验证通过了");} 经常能够看到某个Controler下的Action通过这个标签进行登录权限状态的校验,否则该Action不执行。但是满足什么条件才能通过Authorize这个过滤器的校验呢?答案:↓ public WebApiAp

0评论2023-02-09607

Asp.Net Mvc表单验证方法
   本文所讲的是在Asp.Net MVC框架下所提供的表单验证方法,实现步骤:1.定义验证规则  2.应用验证规则  3.显示验证信息   验证规则:1.Required:必填验证 2Compare:比较验证(验证两个值是否一致)3.StringLength:字符串长度验证(可以单独设置最大值

0评论2023-02-09641

ASP.NET MVC4在View中调用当前Controller中的方法
调用当前Controller中的方法  1 @{2 ((HomeController)ViewContext.Controller).Method1();3 }调用静态方法1 @{2SomeClass.Method();3 } 

0评论2023-02-09552

更多推荐