Register with ASP. net mvc by using the SMS verification code. asp. netmvc

Source: Internet
Author: User

Register with ASP. net mvc by using the SMS verification code. asp. netmvc

 

I used to send text messages to SMS cats. Currently, third-party APIs are mostly used. The general process is:

 

→ The user enters the mobile phone number on the page
→ The user clicks the "get verification code" button to send the mobile phone number to the server. The server generates several digits of random code and stores it somewhere (Session, Applicaiton, database, and so on ), call third-party APIs
→ Third parties send random numbers of digits to users' mobile phones
→ The user enters the received random code on the page
→ Send random codes to the server and compare them with the random codes saved by the server.

 

Take the following interface as an example:

 

 

We need to consider the following aspects:

 

● Mobile phone number: determine the validity of the mobile phone number, compare it with the existing mobile phone number in the database, and determine whether there are duplicates, etc.
● "Get sms verification code" button: Click it and disable it. A 60-second countdown, for example, is displayed. The countdown ends and resumes use.
● "Submit" button: Determine whether the form is verified and whether the verification code is passed before submission.
● The number of times you click the "get sms verification code" button. For example, if you want to restrict the access from the same IP address, you can only click this button three times a day.

 

Select the verification code provider and preparations

 

I chose "cloud News": http://www.ucpaas.com/

 

Register as a "cloud News" user.

 

Go to the "cloud News" management background, and you will see the developer information on the home page, including Account Sid, AuthToken, and Rest URL, which will be used in the future.

 

Click "Application Management", "Application List", and "create application" on the right side of the page. After the application is created, an Application ID is assigned and used. In addition, the created application can be debugged locally only after "cloud News" is approved.

 

Click "Application Management", "SMS management", and "add template" on the right side of the page. On the "add template" Page, enter "content" as follows: the verification code for your registered website {1} is {2}. Please enter the verification code correctly within {3} minutes. After the SMS template is successfully added, a template ID will be assigned, this template ID will also be used. The created SMS template must be approved by cloud messaging before local debugging.

 

Now let's summarize what information we need during development. Including:

 

● Rest URL
● Account Sid
● AuthToken
● Application ID
● SMS template ID
● Content of the short message template, for example, "the verification code for your registered website {1} is {2}. Please enter the verification code correctly within {3} minutes", {1 }, {2} and {3} are placeholders. In an application, you only need to splice a string separated by commas (,), for example, "my website, my verification code, 1"

 

First download a C # Demo, download here: http://www.ucpaas.com/product_service/download, you can find in "REST Server Demo.

 

In addition, the "cloud News" C # Demo uses HttpWebRequest to send a request to the API, in ASP. in. net mvc, we can also use HttpClient to send requests to the API. The request format is as follows:


Http://docs.ucpaas.com/doku.php? Id = rest_api % E4 % BB % 8B % E7 % BB % 8D
Http://docs.ucpaas.com/doku.php? Id = % E7 % 9F % AD % E4 % BF % A1 % E9 % AA % 8C % E8 % AF % 81% E7 % A0 % 81 _ % E6 % A8 % A1 % E6 % 9D % BF % E7 % 9F % AD % E4 % BF % A1

 

During development, sometimes you need to view the returned status code, view here: http://docs.ucpaas.com/doku.php? Id = rest_error

 

Developed under ASP. NET MVC

 

For view models related to user registration, the following class is provided.

 

    public class UserInputVm
    {
[Required (ErrorMessage = "Required")]
[StringLength (16, ErrorMessage = "1-16 characters")]
[Display (Name = "Enter your mobile phone number")]
[RegularExpression (@ "^ 1 [3458] [0-9] {9} $", ErrorMessage = "Incorrect Mobile Phone Number Format")]
        public string LoginName { get; set; } 
    }

 

Above, only consider the legitimacy of the mobile phone input, in reality, also need to judge whether the user input mobile phone number and database already have repeated, use a remote verification feature, refer to here: http://www.cnblogs.com/darrenji/p/3578133.html

 

Create a "Extension" folder under the root directory of the project, and create a UCSRestRequest class. Copy the content and EBodyType enumeration of the UCSRestRequest class in the "cloud News" C # Demo.

 

In HomeController, the Index method sends a view model instance.

 

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new UserInputVm());
        }
        ......
    }

 

 

In the Home/Index. in the cshtml view, click the "send verification code" button to let the button count down and send the phone number to the server. Click the "Submit" button to verify that the verification form has passed, then, send the verification code entered by the user to the server. The form information is submitted only after the verification code is passed.

 

@model MvcApplication2.Models.UserInputVm
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "addForm" }))
{
    @Html.LabelFor(m => m.LoginName)
    @Html.TextBoxFor(m => m.LoginName)
    @Html.ValidationMessageFor(m => m.LoginName)
    <span id="success"></span>
    <br />
    <br />
<Span> enter the verification code. </span>
    <input type="text" id="myCode" />
    <span id="codehint"></span>
<Input type = "button" id = "getCode" value = "click to obtain the verification code"/>
    
    <br />
    <br />
<Input type = "button" id = "up" value = "Submit"/>
}
@section scripts
{
    <script type="text/javascript">
        $(function () {
// Click send verification code
            $('#getCode').on("click", function () {
                checkGetCodeBtn();
                $.post('@Url.Action("GetCheckNum", "Home")', { 'phoneNum': $('#LoginName').val() }, function (data) {
                    if (data.msg) {
$ ('# Success'). text ("Verification Code sent ");
                        alert(data.content);
                    } else {
                        var $getCodeBtn = $('#getCode');
                        clearInterval(t);
                        $getCodeBtn.prop('disabled', false);
$ GetCodeBtn. val ("click to obtain the Verification Code ");
                        count = 60;
                        $('#success').text("");
                    }
                });
            });
// Submit
            $('#up').on("click", function () {
// Verify the correctness of the Verification Code only when the form verification is passed
                if ($('#addForm').valid()) {
                    //clearInterval(t);
                    $.post('@Url.Action("CheckCode", "Home")', { 'checkNum': $('#myCode').val() }, function (data) {
If (data. msg) {// verification code match
                            alert(data.content);
                            $.ajax({
                                cache: false,
                                url: '@Url.Action("Index", "Home")',
                                type: 'POST',
                                dataType: 'json',
                                data: $('#addForm').serialize(),
                                success: function (result) {
                                    if (result.msg) {
                                        alert(result.content);
                                    }
                                },
                                error: function (xhr, status) {
Alert ("submission failed, status Code:" + status );
                                }
                            });
                        } else {
                            $('#codehint').text(data.content);
                        }
                    });
                }
            });
        });
Var count = 60; // start time
Var t; // interval Seed
Var isPass = false; // whether the verification code is entered correctly
        function checkGetCodeBtn() {
// About buttons
            var $getCodeBtn = $('#getCode');
            t = setInterval(function () {
$ GetCodeBtn. val (count + "get again after seconds ");
                $getCodeBtn.prop('disabled', true);
                count--;
                if (count == 0) {
                    clearInterval(t);
                    $getCodeBtn.prop('disabled', false);
$ GetCodeBtn. val ("click to obtain the Verification Code ");
                    count = 60;
                    $('#success').text("");
                }
            }, 1000);
        }
    </script>
}

 

Return to HomeController. There is a method to receive the user's mobile phone number, generate and save the random code, and call the API. There is a method to receive the user's SMS verification code and determine whether it matches; of course, there is also a method to receive form data.

 

    public class HomeController : Controller
    {
        ......
        [HttpPost]
        public ActionResult Index(UserInputVm userInputVm)
        {
            if (ModelState.IsValid)
            {
// Actually save the database here
                //return PartialView("DisplayUser", userInputVm);
                return Json(new {msg=true,content=userInputVm.LoginName});
            }
            else
            {
                return View(userInputVm);
            }
            
        }
// Ask the api to send the verification code to the user's mobile phone
        [HttpPost]
        //[EnableThrottling(PerSecond = 1, PerMinute = 1, PerHour = 3, PerDay = 3)]
        public ActionResult GetCheckNum(string phoneNum)
        {
// TODO: here, I will judge again whether the user's mobile phone number is already in the database.
// Generate a random Verification Code
            Random r = new Random();
            string temMsg = string.Empty;
            for (int i = 0; i < 4; i++)
            {
                temMsg += r.Next(0, 9);
            }
// Save the random code
            //Session["num"] = temMsg;
            //ControllerContext.HttpContext.Application["num"] = temMsg;
// TODO: it is recommended to save the random code to the database, because the SMS, Session, and Application status will be lost when an API is called.
// Splice the text message content
            StringBuilder sb = new StringBuilder();
Sb. appendFormat ("{0}, {1}, {2}", "depending on you", temMsg, "1 "); // The verification code for the website you registered {1} is {2}. Please enter the verification code correctly within {3} minutes
            #region Demo
            string serverIp = "api.ucpaas.com";
            string serverPort = "443";
String account = "Enter the developer's Account Sid here"; // user sid
String token = "Enter the developer's AuthToken here"; // the token corresponding to the user sid
String appId = "Enter the Id of the application that has passed the review"; // the id of the application that has passed the review. Non-test applications must be used online.
String templatedId = "Enter the SMS template ID here"; // SMS template id, which must be reviewed
            //string clientNum = "60000000000001";
            //string clientpwd = "";
            //string friendName = "";
            //string clientType = "0";
            //string charge = "0";
            //string phone = "";
            //string date = "day";
            //uint start = 0;
            //uint limit = 100;
// String toPhone = ""; // send the SMS number, separated by commas (,).
// String param = ""; // SMS parameter a, B, c
            //string verifyCode = "1234";
            //string fromSerNum = "4000000000";
            //string toSerNum = "4000000000";
            //string maxallowtime = "60";
            UCSRestRequest api = new UCSRestRequest();
            api.init(serverIp, serverPort);
            api.setAccount(account, token);
            api.enabeLog(true);
            api.setAppId(appId);
            api.enabeLog(true);
            string feedback = api.SendSMS(phoneNum, templatedId, sb.ToString()); 
            #endregion
            return Json(new { msg = true, content = feedback });
        }
// Check the verification code
        [HttpPost]
        public ActionResult CheckCode(string checkNum)
        {
            try
            {
// Obtain the stored random text message verification code from the database.
// Actually, the Application ["num"] or Session ["num"] data status is lost.
                if (ControllerContext.HttpContext.Application["num"] != null)
                {
                    string temp = ControllerContext.HttpContext.Application["num"].ToString();
                    if (checkNum == temp)
                    {
                        return Json(new { msg = true, content = temp });
                    }
                    else
                    {
Return Json (new {msg = false, content = "The Verification Code does not match. Please enter it again "});
                    }
                }
                else
                {
Return Json (new {msg = false, content = "invalid verification code, please retrieve it again "});
                }
                
            }
            catch (Exception ex)
            {
                
                throw;
            }
        }        
    }

 

Above,

 

● The Index method under [HttpPost] is used to receive and save form data.

 

● The GetCheckNum method receives the user's mobile phone number. You must note the following:

 

1. EnableThrottling is used to limit the number of requests from the same IP address within the unit time interval. For how to use it, refer to here: http://www.cnblogs.com/darrenji/p/4446767.html

 

2. Do not save the random text message verification code to the Session or Application. Because the Demo actually uses HttpWebRequest to send a request to the API and opens another thread, the Session or Application status will be lost, we recommend that you save the random SMS verification code to the database.

 

3. Although the front-end page can determine whether the user's entered mobile phone number is already in the database, it is still possible for a single user to send the duplicate mobile phone number to the server, in this method on the server end, it is necessary to determine whether the user's mobile phone number is repeated again.

 

4. Different Demo methods can also be used to send requests to APIs.

 

● The CheckCode method is used to receive the user's SMS verification code. We recommend that you compare the Received verification code with the verification code of the mobile phone number in the database.

 


Finally, I would like to thank UIT studio for recommending "cloud News" and providing the HttpClient call code reference. Thanks to the cooperation of the "cloud News" team members who are: Cathy @ cloud news, ada @ cloud news, Auspicious @ cloud news, and so on.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.