asp.net mvc 短信验证码

 

 

把发短信功能写成一个类包,需要引用:

SmsUtillity.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;


//到吉信通申请试用账号
namespace ProcuracyRoom.Dll
{
    public sealed class SmsUtility : ISmsUtility
    {
        //这里使用的是吉信通,注册个账号密码 联系管理员 让他给你开通测试就可以,应该能有几块钱的短信费
        private string url = "http://service.winic.org:8009/sys_port/gateway/index.asp";
        private string id = "onepiece";//账号
        private string pass = "521000";//密码
        public Sms send(string phone, string content)
        {
            Stream stream;
            //发送中文内容时,首先要将其进行编码成 %0D%AC%E9 这种形式
            byte[] data = Encoding.GetEncoding("GB2312").GetBytes(content);
            string encodeContent = "";
            foreach (var b in data)
            {
                encodeContent += "%" + b.ToString("X2");
            }
            //string temp = string.Format("{0}?id={1}&pwd={2}&to={3}&content={4}", url, id, pass, phone, content);
            string temp = string.Format("{0}?id={1}&pwd={2}&to={3}&content={4}", url, id, pass, phone, encodeContent);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(temp);            
            request.ContentType = "text/html;charset=GB2312";
            request.Method = "GET"; 
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("GB2312"));
            string text = reader.ReadToEnd();
            reader.Close();
            stream.Close();
            Sms status = Sms.parse(text);            
            return status;
        } 
    }

    public interface ISmsUtility
    {
        Sms send(string phone, string content);
    }
    public  class Sms
    {
        public string SmsStatus { get; set; }
        public bool Success { get; set; }
        public double CostMoney { get; set; }
        public double RemainMoney { get; set; }
        public string SmsId { get; set; }
        public static Sms parse(string text)
        {
            string[] words = text.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            if (words.Length != 5) throw new ApplicationException("字符串格式不正确");
            Sms result = new Sms();
            result.SmsStatus = words[0];
            result.Success = words[0] == "000";
            result.CostMoney = double.Parse(afterComma(words[2]));
            result.RemainMoney = double.Parse(afterComma(words[3]));
            result.SmsId = afterComma(words[4]);
            return result;
        }
        private static string afterComma(string text)
        {
            int n = text.IndexOf(':');
            if (n < 0) return text;
            return text.Substring(n + 1);
        }
    }
}

View部分:

@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <link href="~/Content/bootstrap.min.css" rel="stylesheet" />
    <script src="~/Scripts/jquery-1.11.2.min.js"></script>
    <script src="~/Scripts/bootstrap.min.js"></script>
    <title>Index</title>
    <script type="text/javascript">
        window.onload = function () {
            var InterValObj; //timer变量,控制时间
            var count = 60; //间隔函数,1秒执行
            var curCount;//当前剩余秒数
            var code = ""; //验证码
            var codeLength = 6;//验证码长度
            $("#getcode").click(function () {

                //获取输入的手机号码
                var phoNum = $("#phone").val();
                //alert(phoNum);
                curCount = count;
                $.getJSON('/Admin/GetCode/', { phoNum: phoNum }, function (result) {

                    if (result) {
                        // 设置按钮显示效果,倒计时
                        $("#getcode").attr("disabled", "true");
                        $("#getcode").val("请在" + curCount + "秒内输入验证码");
                        InterValObj = window.setInterval(SetRemainTime, 1000); // 启动计时器,1秒执行一次
                    } else {
                        $("#getcode").val("重新发送验证码");
                    }
                });
            });
            //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: "/Admin/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;
                        }
                    }
                });
            });
        }
    </script>
</head>
<body>
    <form class="form-horizontal" role="form">
        <div class="form-group">
            <label class="col-sm-2 control-label">用户名</label>
            <div class="col-sm-6">
                <input type="text" style="width: 300px;" class="form-control" id="Name" placeholder="用户名">
            </div>
        </div>
        <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="phone" 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>
</body>
</html>

AdminContorller部分:

using ChengJiDaoRuChaXun.Dao;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ProcuracyRoom.Dll;

namespace ChengJiDaoRuChaXun.Controllers
{
    public class AdminController : Controller
    {      
        public ActionResult Index(string m)
        {
            return View();
        }
        #region GetCode()-获取验证码
        /// <summary>
        /// 返回json到界面
        /// </summary>
        /// <returns>string</returns>
        public ActionResult GetCode(string phoNum)
        {
            try
            {
                bool result;
                string code = "";
                //随机生成6位短信验证码    
                Random rand = new Random();
                for (int i = 0; i < 6; i++)
                {
                    code += rand.Next(0, 10).ToString();
                }
                // 短信验证码存入session(session的默认失效时间30分钟) 
                Session.Add("code", code);
                Session["CodeTime"] = DateTime.Now;//存入时间一起存到Session里
                // 短信内容+随机生成的6位短信验证码    
                String content = "【欢迎注册】 您的注册验证码为:" + code + ",如非本人操作请联系磊哥。";

                // 单个手机号发送短信
                SmsUtility su = new SmsUtility();
                if (su.send(phoNum, content).Success)
                {
                    result = true;// 成功    
                }
                else {
                    result = false;//失败    
                }

                return Json(result, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region CheckCode()-检查验证码是佛正确
        public ActionResult CheckCode()
        {
            bool result = false;
            //用户输入的验证码
            string checkCode = Request["CheckCode"].Trim();
            //取出存在session中的验证码
            string code = Session["code"].ToString();
            DateTime time = (DateTime)Session["CodeTime"];
            try
            {
                //验证是否一致并且产生验证码的时间+60秒与当前时间相比较是否小于60
                if (checkCode != code || time.AddSeconds(60) < DateTime.Now)
                {
                    
                    result = false;
                }
                else
                {
                    result = true;
                }

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

 

posted on 2019-06-13 15:30  sxjljj  阅读(898)  评论(1编辑  收藏  举报