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
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM