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 = "";//密码
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 != ) throw new ApplicationException("字符串格式不正确");
Sms result = new Sms();
result.SmsStatus = words[];
result.Success = words[] == "";
result.CostMoney = double.Parse(afterComma(words[]));
result.RemainMoney = double.Parse(afterComma(words[]));
result.SmsId = afterComma(words[]);
return result;
}
private static string afterComma(string text)
{
int n = text.IndexOf(':');
if (n < ) return text;
return text.Substring(n + );
}
}
}
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 = ; //间隔函数,1秒执行
var curCount;//当前剩余秒数
var code = ""; //验证码
var codeLength = ;//验证码长度
$("#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, ); // 启动计时器,1秒执行一次
} else {
$("#getcode").val("重新发送验证码");
}
});
});
//timer处理函数
function SetRemainTime() {
if (curCount == ) {
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 = ; i < ; i++)
{
code += rand.Next(, ).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() < DateTime.Now)
{ result = false;
}
else
{
result = true;
} return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
throw new Exception("短信验证失败", e);
}
}
#endregion
}
}
asp.net mvc 短信验证码的更多相关文章
- asp.net mvc短信接口调用——阿里大于API开发心得
互联网上有许多公司提供短信接口服务,诸如网易云信.阿里大于等等.我在自己项目里需要使用到短信服务起到通知作用,实际开发周期三天,完成配置.开发和使用,总的说,阿里大于提供的接口易于开发,非常的方便,短 ...
- 在ASP.NET MVC下通过短信验证码注册
以前发短信使用过短信猫,现在,更多地是使用第三方API.大致过程是: → 用户在页面输入手机号码→ 用户点击"获取验证码"按钮,把手机号码发送给服务端,服务端产生几位数的随机码,并 ...
- 请给你的短信验证码接口加上SSL双向验证
序言 去年年底闲来几天,有位同事专门在网上找一些注册型的app和网站,研究其短信接口是否安全,半天下来找到30来家,一些短信接口由于分析难度原因,没有继续深入,但差不多挖掘到20来个,可以肆意被调用, ...
- SSH2框架实现注冊发短信验证码实例
这两天開始写程序了,让用SSH2框架,曾经没有接触过Java项目更没有接触过SSH2框架,所以用注冊開始了我Java之旅.后来发现,后台代码挺easy理解的,跟.net的差点儿相同.就是层与层之间的调 ...
- Atitit. 破解 拦截 绕过 网站 手机 短信 验证码 方式 v2 attilax 总结
Atitit. 破解 拦截 绕过 网站 手机 短信 验证码 方式 v2 attilax 总结 1. 验证码的前世今生11.1. 第一代验证码 图片验证码11.2. 第二代验证码 用户操作 ,比如 ...
- jQuery获取短信验证码+倒计时实现
jQuery 短信验证码倒计时 <script type="text/javascript" charset="utf-8"> $(function ...
- 转载:Android自动化测试- 自动获取短信验证码
前言:android应用的自动化测试必然会涉及到注册登录功能,而许多的注册登录或修改密码功能常常需要输入短信验证码,因此有必要能够自动获得下发的短信验证码. 主要就是实时获取短信信息. android ...
- App开发(Android与php接口)之:短信验证码
最近和同学们一起开发一个自主项目,要用到短信验证码,在网上搜索了很久,看到一个推荐贴,提到了很多不错的短信服务商.经过测试,帖子中提到的服务商他们的短信到达率和到达速度也都不错.最后,由于经费问题,我 ...
- android自动获取短信验证码
前言:android应用的自动化测试必然会涉及到注册登录功能,而许多的注册登录或修改密码功能常常需要输入短信验证码,因此有必要能够自动获得下发的短信验证码.主要就是实时获取短信信息.android上获 ...
随机推荐
- tensorflow之tensorboard
参考https://www.cnblogs.com/felixwang2/p/9184344.html 边学习,边练习 # https://www.cnblogs.com/felixwang2/p/9 ...
- 【C语言】判断某一正整数是否为完数
什么是完数? 如果一个数等于它的因子之和,则称该数为“完数”(或“完全数”). 例如,6的因子为1.2.3,而 6=1+2+3,因此6是“完数”. 程序框图:m 问题分析 根据完数的定义,解决本题的 ...
- IDEA启动报错-java.net.BindException: Address already in use: bind
启动IDEA报错日志如下: Internal error. Please refer to http://jb.gg/ide/critical-startup-errors java.net.Bind ...
- 数据库单,多,全库、冷热备份思路及备份与还原(mysqldump)
热备份:服务开启状态下进行备份, 冷备份:服务关闭状态进行备份, 冷备份 数据库原有内容如下: MariaDB [(none)]> show databases;+--------------- ...
- php 算false的情况
四.PHP中算false的情况 1.Boolan false 2.整形 0 3.浮点型 0.0 4.字符串"" "0" ("0.0" &qu ...
- ES5-bind用法及与以前的apply和call
当我们调用一个函数的时候,函数中的this一般是指向调用者的.但是我们其实可以在调用函数的时候,传入一个对象,让函数中的this指向我们传入的对象,而不是调用者本身. apply,call,bind都 ...
- 吴裕雄--天生自然Numpy库学习笔记:NumPy 字节交换
大端模式:指数据的高字节保存在内存的低地址中,而数据的低字节保存在内存的高地址中,这样的存储模式有点儿类似于把数据当作字符串顺序处理:地址由小向大增加,而数据从高位往低位放 小端模式:指数据的高字节保 ...
- 转专业后补修C语言的一些体会(3)
1.指针:指针是C语言最为强大的工具之一,有着很多优点,比如可以改善子程序的效率,为动态数据结构提供支持,为C的动态内存分配系统提供支持,为函数提供修改变量值的手段.但指针的使用十分困难.会出现很多意 ...
- idea maven项目使用过程中遇到的问题
1. Error:Cannot build Artifact :war exploded because it is included into a circular depency 参考: http ...
- I/O-<File区别>
FileInputStream FileOutputStream ObjectInputStream ObjectOutputStream 传的是对象 需要新建一 ...