ASP.NET MVC+Bootstrap 实现短信验证

短信验证大家都已经很熟悉了,基本上每天都在接触手机短信的验证码,比如某宝,某东购物,网站注册,网上银行等等,都要验证我们的手机号码真实性。这样做有什么好处呢。


以前咱们在做网站的时候,为了提高用户注册的质量,防止用户恶意注册,都会设置一些小阻碍,如网页验证码、邮件认证等等。但是道高一尺魔高一丈,很快网站的这些设置都被一些网络黑客利用注册机逐一攻破,这些功能也就随之变成了摆设。


但是魔高一丈道高两丈,随着移动设备的普及,短信验证的功能横空出世。他的出现轻松的排除了传统网站验证码的弊端,还提升了网站用户注册的质量,并且可以更有效的管理网站注册用户,随时与之保持联系和沟通。另外,用户的手机号码还可以做绑定,衍生出更多的应用,比如手机密码找回,手机发送指令,手机帐号和用户注册帐号可做同步登录、同步通讯录、同步更多手机相关的应用等。


手机短信验证,听上去很复杂的样子,但是看完下面这个图你就会恍然大悟!

原理图:


原理图


其原理就是,当用户在网站上注册的时候,系统会要求用户输入自己的手机号码,点击发送验证码时,系统会调用第三方短信平台提供的接口,将用户手机号码和系统自动生成的验证码,提供给平台,然后由平台将短信验证码发送至用户的手机。当然系统在调用接口之前,会将生成的验证码保存至缓存一份;用户收到验证码后输入对话框,提交后系统验证用户输入的和缓存中保存的验证码是否一致,一致方可完成注册。


Demo

所用工具:Bootstrap框架,ASP.NET MVC,天下畅通平台接口。


View Code

@{
    ViewBag.Title = "Index";
}
<link href="../../Content/bootstrap-3.3.0-dist/dist/css/bootstrap.min.css" rel="stylesheet" />
<script src="../../Content/bootstrap-3.3.0-dist/dist/js/jquery-1.11.2.min.js"></script>
<script src="../../Content/bootstrap-3.3.0-dist/dist/js/bootstrap.min.js"></script>
<script src="../../Scripts/MyScripts/Register.js"></script>

<div class="hero-unit" contenteditable="true">
    <h1>某网站注册</h1>
    <p>学的不仅是技术,更是梦想!</p>
    <p>
        再牛逼的梦想,也抵不住你傻逼似的坚持!
    </p>
</div>

<br>
<br>
<br>
<br>
<br>

<form class="form-horizontal" role="form">
    <div class="form-group">
        <label for="inputEmail3" class="col-sm-2 control-label">手机号</label>
        <div class="col-sm-6">
            <div style="float: left;">
                <input id="phonum" type="text" class="form-control" style="width: 300px;">
            </div>
            <div style="float: left;">
                <input class="btn btn-info" type="button" id="getcode" value="点击获取手机验证码" />
                <span id="telephonenameTip"></span>
            </div>
        </div>
    </div>

    <div class="form-group">
        <label class="col-sm-2 control-label">验证码</label>
        <div class="col-sm-6">
            <input style="width: 300px;" class="form-control" id="codename">
            <span id="codenameTip"></span>
        </div>
    </div>

    <div class="form-group">
        <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
        <div class="col-sm-6">
            <input type="password" style="width: 300px;" class="form-control" id="" placeholder="Password">
        </div>
    </div>

    <div class="form-group">
        <div class="col-sm-offset-2 col-sm-6">
            <button type="button" id="submit" class="btn btn-primary">立即注册</button>
        </div>
    </div>
</form>

JS Code


/************************************************* 
作者: 牛迁迁
小组: 
说明:短信验证所用到的JS方法,此实例仅作为Demo,一些验证暂时省略。
创建日期:2015年8月11日 17:55:40
版本号:V1.0.0
**********************************************/

window.onload = function () {

    //短信验证码  
    var InterValObj; //timer变量,控制时间    
    var count = 60; //间隔函数,1秒执行    
    var curCount;//当前剩余秒数    
    var code = ""; //验证码    
    var codeLength = 6;//验证码长度   

    $("#getcode").click(function () {

        //获取输入的手机号码
        var phoNum = $("#phonum").val();
        //alert(phoNum);
        curCount = count;

        //用正则表达式验证手机号是否合法
        //var re = /(^1[3|5|8][0-9]{9}$)/;
        //略
        // 产生随记验证码    
        for (var i = 0; i < codeLength; i++) {
            code += parseInt(Math.random() * 9).toString();
        }

        // 设置按钮显示效果,倒计时   
        $("#getcode").attr("disabled", "true");
        $("#getcode").val("请在" + curCount + "秒内输入验证码");
        InterValObj = window.setInterval(SetRemainTime, 1000); // 启动计时器,1秒执行一次    

        // 向后台发送处理数据    
        $.ajax({
            type: "POST", // 用POST方式传输    
            dataType: "text", // 数据格式:JSON    
            url: "/Register/GetCode", // 目标地址    
            data: { "Code": code, "phoNum": phoNum },
            error: function (msg) {
                alert(msg);
            },
            success: function (data) {
                //前台给出提示语
                if (data == "true") {
                    $("#telephonenameTip").html("<font color='#339933'>√ 短信验证码已发到您的手机,请查收(30分钟内有效)</font>");
                } else if (data == "false") {
                    $("#telephonenameTip").html("<font color='red'>× 短信验证码发送失败,请重新发送</font>");
                    return false;
                }
            }
        });

    });

    //timer处理函数    
    function SetRemainTime() {
        if (curCount == 0) {
            window.clearInterval(InterValObj);// 停止计时器    
            $("#getcode").removeAttr("disabled");// 启用按钮    
            $("#getcode").val("重新发送验证码");
            code = ""; // 清除验证码。如果不清除,过时间后,输入收到的验证码依然有效    
        } else {
            curCount--;
            $("#getcode").val("请在" + curCount + "秒内输入验证码");
        }
    }

    //提交注册按钮
    $("#submit").click(function () {
        var CheckCode = $("#codename").val();
        // 向后台发送处理数据    
        $.ajax({
            url: "/Register/CheckCode",
            data: { "CheckCode": CheckCode },
            type: "POST",
            dataType: "text",
            success: function (data) {
                if (data == "true") {
                    $("#codenameTip").html("<font color='#339933'>√</font>");
                } else {
                    $("#codenameTip").html("<font color='red'>× 短信验证码有误,请核实后重新填写</font>");
                    return;
                }
            }
        });
    });
}

Controller Code


    public class RegisterController : Controller
    {

        //短信验证码接口的测试数据(天下畅通平台给参数)  
        public static String url = "http://xtx.telhk.cn:8080/sms.aspx";
        public static String userid = "****";
        public static String account = "****";
        public static String password = "****";

        public ActionResult Index()
        {
            return View();
        }


        #region GetCode()-获取验证码-牛迁迁-2015年8月8日 11:12:37
        /// <summary>
        /// 返回json到界面
        /// </summary>
        /// <returns>string</returns>
        public ActionResult GetCode()
        {
            try
            {
                bool result;
                //接收前台传过来的参数。短信验证码和手机号码
                string code = Request["Code"];
                string phoNum = Request["phoNum"];

                // 短信验证码存入session(session的默认失效时间30分钟) 
                //也可存入Memcached缓存
                Session.Add("code", code);

                // 短信内容+随机生成的6位短信验证码    
                String content = "【欢迎注册今日开讲】 您的注册验证码为:" + code + ",如非本人操作请忽略。有疑问请联系我们:http://blog.csdn.net/u010028869";

                // 单个手机号发送短信
                if (!SendMessage(content, phoNum, url, userid, password, account))
                {
                    result = false;// 失败    
                }
                else
                {
                    result = true;// 成功    
                }
                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        /// <summary>
        /// 核心功能-短信发送方法
        /// </summary>
        /// <param name="content">短信内容</param>
        /// <param name="phoNum">手机号码</param>
        /// <param name="url">请求地址</param>
        /// <param name="userid">企业id</param>
        /// <param name="password">密码</param>
        /// <param name="account">用户帐号</param>
        /// <returns>bool 是否发送成功</returns>
        public bool SendMessage(string content, string phoNum, string url, string userid, string password, string account)
        {
            try
            {
                Encoding myEncoding = Encoding.GetEncoding("UTF-8");
                //按照平台给定格式,组装发送参数 包括用户id,密码,账户,短信内容,账户等等信息
                string param = "action=send&userid=" + userid + "&account=" + HttpUtility.UrlEncode(account, myEncoding) + "&password=" + HttpUtility.UrlEncode(password, myEncoding) + "&mobile=" + phoNum + "&content=" + HttpUtility.UrlEncode(content, myEncoding) + "&sendTime=";

                //发送请求
                byte[] postBytes = Encoding.ASCII.GetBytes(param);
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                req.ContentLength = postBytes.Length;

                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(postBytes, 0, postBytes.Length);
                }


                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                //获取返回的结果
                using (WebResponse wr = req.GetResponse())
                {
                    StreamReader sr = new StreamReader(wr.GetResponseStream(), System.Text.Encoding.UTF8);
                    System.IO.StreamReader xmlStreamReader = sr;
                    //加载XML文档
                    xmlDoc.Load(xmlStreamReader);
                }
                //解析XML文档,进行相应判断
                if (xmlDoc == null)
                {
                    return false;
                }
                else
                {
                    String message = xmlDoc.GetElementsByTagName("message").Item(0).InnerText.ToString();
                    if (message == "ok")
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        #region CheckCode()-检查验证码是否正确-牛迁迁-2015年8月8日 11:12:37
        public ActionResult CheckCode()
        {
            bool result = false;
            //用户输入的验证码
            string checkCode = Request["CheckCode"].Trim();
            //取出存在session中的验证码
            string code = Session["code"].ToString();
            try
            {
                //验证是否一致
                if (checkCode != code)
                {
                    result = false;
                }
                else
                {
                    result = true;
                }

                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                throw new Exception("短信验证失败", e);
            }
        }
        #endregion
    }

显示效果:


发送短信:

这里写图片描述


接收短信:

这里写图片描述


验证短信:

这里写图片描述




很简单的短信验证功能就实现了,现在网上有很多提供短信验证码服务的公司,而且也都会提供一定的免费发送次数。大家可以做个Demo尝试一下。



点击下载博客Demo源代码

  • 13
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 64
    评论
Combine the power of ASP.Net MVC 6 with Bootstrap 4 to build elegant, responsive web apps About This Book Updated for Bootstrap 4 and ASP.Net MVC 6, this book shows how to take advantage of the latest new features introduced in both of these industry-leading frameworks Build responsive, mobile-ready apps by combining the power of ASP.NET MVC with Bootstrap Grasp the intricacies of Bootstrap and how to use it with ASP.NET MVC Build your own tools and helpers to assist you in creating ASP.NET MVC Bootstrap sites easily and quickly Master the use of Bootstrap components and plugins with ASP.NET MVC Who This Book Is For If you are an ASP.NET MVC developer and would like to know how to incorporate Bootstrap into your projects, then this book is invaluable to you. Developers with entry-level experience of ASP.NET MVC development and limited experience with Bootstrap will also benefit from this book. What You Will Learn Create a new ASP.Net MVC 6 project that uses Bootstrap for its styling and learn how to include external libraries using the new package managers Learn to use the various Bootstrap CSS and HTML elements, and how to use the new Bootstrap 4 grid layout system with ASP.Net MVC Explore the different input groups and implement alerts, progress bars, and badges Explore JavaScript components by illustrating and walking through the process of using JavaScript/JQuery to add interactivity to Twitter Bootstrap components Build your own ASP.Net MVC helpers and tag helpers to reduce the amount of HTML needed to generate Bootstrap elements in your projects Convert a Bootstrap HTML template into a usable ASP.Net MVC project Use the jQuery DataTables plugin with Bootstrap and ASP.Net MVC Learn to include and use the TwitterBootstrapMVC library in an ASP.Net MVC project In Detail One of the leading open source frontend frameworks, Bootstrap has undergone a significant change and introduced several features that make designing compelling, next-generation UIs much simpler.
包括源代码、数据库文档、数据库创建SQL脚本。一套基于ASP.NET MVC+EF6+Bootstrap开发出来的框架源代码! 采用主流框架,容易上手,简单易学,学习成本低。可完全实现二次开发、基本满足80%项目需求。 可以帮助解决.NET项目70%的重复工作,让开发更多关注业务逻辑。既能快速提高开发效率,帮助公司节省人力成本,同时又不失灵活性。 支持SQLServer、MySQL、Oracle、SQLite、Access 等多数据库类型。模块化设计,层次结构清晰。内置一系列企业信息管理的基础功能。 操作权限控制精密细致,对所有管理链接都进行权限验证,可控制到导航菜单、功能按钮。 数据权限(精细化数据权限控制,控制到行级,列表级,表单字段级,实现不同人看不同数据,不同人对同一个页面操作不同字段 兼容目前最流行浏览器(IE8+、Chrome、Firefox、360浏览器) 1、前端技术 JS框架:Bootstrap、JQuery CSS框架:Bootstrap v3.3.4(稳定是后台,UI方面根据需求自己升级改造吧)。 客户端验证:jQuery Validation Plugin。 在线编辑器:ckeditor、simditor 上传文件:Uploadify 数据表格:jqGrid、Bootstrap Talbe 对话框:layer 页面布局:jquery.layout.js 图表插件:echarts、highcharts 2、后端技术 核心框架:ASP.NET MVC5、WEB API 持久层框架:EntityFramework 定时计划任务:Quartz.Net组件 安全支持:过滤器、Sql注入、请求伪造 服务端验证:实体模型验证、自己封装Validator 缓存框架:微软自带Cache、Redis 日志管理:Log4net、登录日志、操作日志 工具类:NPOI、Newtonsoft.Json、验证码

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 64
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值