手机发送短信验证是调用第三方控件,利用第三方平台实现的
首先要在web层进行配置,代码如下:
<add key="WebReference.Service.PostUrl" value="http://106.ihuyi.cn/webservice/sms.php?method=Submit"/>
<add key="WebReference.sms" value="http://106.ihuyi.cn/webservice/sms.php?smsService"/>
然后是Controller层,代码如下:
#region 发送短信验证码
public static string PostUrl = ConfigurationManager.AppSettings["WebReference.Service.PostUrl"];
public void Page_Load(string phone)
{
string account = "C09783861";//用户名是登录用户中心->验证码、通知短信->帐户及签名设置->APIID
string password = "995c642c8aa6f1e0bf5d88da80778e7f"; //密码是请登录用户中心->验证码、通知短信->帐户及签名设置->APIKEY
string mobile = phone;
Random rad = new Random();
int mobile_code = rad.Next(1000, 10000);
string content = "您的验证码是:" + mobile_code + " 。请不要把验证码泄露给其他人。";
Session["mobile_code"] = mobile_code;
Session["mobile_code"] = mobile_code;
Session["mobile"] = mobile;
string postStrTpl = "account={0}&password={1}&mobile={2}&content={3}";
UTF8Encoding encoding = new UTF8Encoding();
byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content));
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(PostUrl);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = postData.Length;
Stream newStream = myRequest.GetRequestStream();
// Send the data.
newStream.Write(postData, 0, postData.Length);
newStream.Flush();
newStream.Close();
HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
if (myResponse.StatusCode == HttpStatusCode.OK)
{
StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
//Response.Write(reader.ReadToEnd());
string res = reader.ReadToEnd();
int len1 = res.IndexOf("</code>");
int len2 = res.IndexOf("<code>");
string code = res.Substring((len2 + 6), (len1 - len2 - 6));
//Response.Write(code);
int len3 = res.IndexOf("</msg>");
int len4 = res.IndexOf("<msg>");
string msg = res.Substring((len4 + 5), (len3 - len4 - 5));
Response.Write(msg);
Response.End();
}
else
{
//访问失败
}
}
//匹配验证码
public ActionResult take()
{
string mobile_code = Session["mobile_code"].ToString();
return Json(mobile_code, JsonRequestBehavior.AllowGet);
}
#endregion
最后就是JQ、JS层代码:
//发送短信验证码
window.onload = function () {
$("#verification").click(function () {
var phone = $("#phone").val();
$.post("/Main/Page_Load", { phone: phone }, function (msg) {
if (msg == true) {
layer.alert("已发送", { icon: 1, title: '提示' });
} else {
layer.alert("已发送", { icon: 1, title: '提示' });
}
});
});
//验证码验证是否匹配
$("#register").click(function () {
var JudgmentCode = $("#JudgmentCode").val();
$.post("/Main/take", function (msg) {
if (JudgmentCode.toString().trim() == msg.trim()) {
layer.alert("动态口令正确", { icon: 1, title: '提示' });
} else {
layer.alert("请输入或不正确", { icon: 2, title: '提示' });
}
});
});
}
至于视图代码就不写了,视图可以千变万化,只要有最基本的几个输入框和几个按钮就行。