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上获 ...
随机推荐
- Educational Codeforces Round 77 (Rated for Div. 2)D(二分+贪心)
这题二分下界是0,所以二分写法和以往略有不同,注意考虑所有区间,并且不要死循环... #define HAVE_STRUCT_TIMESPEC #include<bits/stdc++.h> ...
- LA 3708 墓地雕塑(模拟)
题目链接:https://vjudge.net/problem/UVALive-3708 这道题的思路也是比较难想. 首先根据上一题(Uva 11300)可知,要想让移动距离最短,那么至少要使一个雕塑 ...
- 使用JavaScript获取样式的属性值
1 . 在js中可以使用style属性来获取样式的属性值(只能获取内联样式的属性值) 语法格式为: HTML元素.style.样式属性; 2 . 在IE浏览器中,使用currentStyle来获取 ...
- 「HNOI/AHOI2018」游戏
传送门 Luogu 解题思路 这是一道 \(O(n^2)\) 暴力加上 \(\text{random_shuffle}\) 优化 什么鬼 就可以 \(\text{AC}\) 的题. 但还是要讲一下 \ ...
- stl_list复习
#include <iostream>#include <list>#include <algorithm>using namespace std; //底层结构是 ...
- .NET Core快速入门教程 3、使用VS Code开发.NET Core控制台应用程序
一.前言 本篇开发环境 1.操作系统: Windows 10 X642.SDK: .NET Core 2.0 Preview3.VS Code:1.14 二.安装&配置 1.VS Code下载 ...
- 中山纪中Day1--普及
早上一起,扑面是瓢泼的大雨.跨过千山万水,来到纪中门前,毅然以一种大无畏的英雄气概跨进了考场. 面对四道神题.然后,我成功过五关斩六将,A掉了2道题!!! 收获:优先队列(大.小根堆) T1:APPL ...
- pikachu-搜索型注入 #手工注入
1.搜索型注入漏洞产生的原因: 在搭建网站的时候为了方便用户搜索该网站中的资源,程序员在写网站脚本的时候加入了搜索功能,但是忽略了对搜索变量的过滤,造成了搜索型注入漏洞,又称文本框注入. 2.搜索型注 ...
- JAVA(1)之关于对象数组作形参名的方法的使用
public class Test{ int tour; public static void cs(Test a[]) { for (int i = 0; i < a.length; i++) ...
- Linux 下忘记mysql 密码
ERROR (): Access denied for user 'root'@'localhost' (using password: YES). 一.停止 mysql 数据库 /etc/init. ...