把发短信功能写成一个类包,需要引用:

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 短信验证码的更多相关文章

  1. asp.net mvc短信接口调用——阿里大于API开发心得

    互联网上有许多公司提供短信接口服务,诸如网易云信.阿里大于等等.我在自己项目里需要使用到短信服务起到通知作用,实际开发周期三天,完成配置.开发和使用,总的说,阿里大于提供的接口易于开发,非常的方便,短 ...

  2. 在ASP.NET MVC下通过短信验证码注册

    以前发短信使用过短信猫,现在,更多地是使用第三方API.大致过程是: → 用户在页面输入手机号码→ 用户点击"获取验证码"按钮,把手机号码发送给服务端,服务端产生几位数的随机码,并 ...

  3. 请给你的短信验证码接口加上SSL双向验证

    序言 去年年底闲来几天,有位同事专门在网上找一些注册型的app和网站,研究其短信接口是否安全,半天下来找到30来家,一些短信接口由于分析难度原因,没有继续深入,但差不多挖掘到20来个,可以肆意被调用, ...

  4. SSH2框架实现注冊发短信验证码实例

    这两天開始写程序了,让用SSH2框架,曾经没有接触过Java项目更没有接触过SSH2框架,所以用注冊開始了我Java之旅.后来发现,后台代码挺easy理解的,跟.net的差点儿相同.就是层与层之间的调 ...

  5. Atitit. 破解  拦截 绕过 网站 手机 短信 验证码  方式 v2 attilax 总结

    Atitit. 破解  拦截 绕过 网站 手机 短信 验证码  方式 v2 attilax 总结 1. 验证码的前世今生11.1. 第一代验证码 图片验证码11.2. 第二代验证码  用户操作 ,比如 ...

  6. jQuery获取短信验证码+倒计时实现

    jQuery 短信验证码倒计时 <script type="text/javascript" charset="utf-8"> $(function ...

  7. 转载:Android自动化测试- 自动获取短信验证码

    前言:android应用的自动化测试必然会涉及到注册登录功能,而许多的注册登录或修改密码功能常常需要输入短信验证码,因此有必要能够自动获得下发的短信验证码. 主要就是实时获取短信信息. android ...

  8. App开发(Android与php接口)之:短信验证码

    最近和同学们一起开发一个自主项目,要用到短信验证码,在网上搜索了很久,看到一个推荐贴,提到了很多不错的短信服务商.经过测试,帖子中提到的服务商他们的短信到达率和到达速度也都不错.最后,由于经费问题,我 ...

  9. android自动获取短信验证码

    前言:android应用的自动化测试必然会涉及到注册登录功能,而许多的注册登录或修改密码功能常常需要输入短信验证码,因此有必要能够自动获得下发的短信验证码.主要就是实时获取短信信息.android上获 ...

随机推荐

  1. jQuery中$.fn

    $.fn是指jquery的命名空间,加上fn上的方法及属性,会对jquery实例每一个有效. 如扩展$.fn.abc(),即$.fn.abc()是对jquery扩展了一个abc方法,那么后面你的每一个 ...

  2. linux 系统 grep 命令 摘录过滤特定的行

    1.grep ‘xxx’ filename  enter   其中xxx为要搜索的字符串 ,即可检索到含有 xxx的行. 2.grep 'xxx' filename  >newfilename ...

  3. Hbuilder实用快捷键

    Ctrl + d                   删除整行内容 Ctrl + Shift +R            复制当前行到下一行 Ctrl + Shift +D               ...

  4. Python - int()

    参考 https://docs.python.org/3/library/functions.html?highlight=int#int If x is not a number or if bas ...

  5. Vulnhub_DC7 记录

    基本步骤 经验 & 总结 对信息还是不敏感,其实也是因为对Drupal这个CMS并不熟悉,不知道哪些地方是默认的那些地方是作者修改,比如这个"DC7USER". 对Drup ...

  6. selenium 元素查找与属性

    1.首先你要安装selenium库啦 pip install selenium 2.selenium查找元素就八种方法 from selenium import webdriver driver=we ...

  7. Spring Boot 中使用 HttpClient 进行 POST GET PUT DELETE

    有的时候,我们的 Spring Boot 应用需要调用第三方接口,这个接口可能是 Http协议.可能是 WebService.可能是 FTP或其他格式,本章讨论 Http 接口的调用. 通常基于 Ht ...

  8. 线程同步 - POSIX互斥锁

    线程同步 - POSIX互斥锁 概括 本文讲解POSIX中互斥量的基本用法,从而能达到简单的线程同步.互斥量是一种特殊的变量,它有两种状态:锁定以及解锁.如果互斥量是锁定的,就有一个特定的线程持有或者 ...

  9. C语言-(void*)类型指针

    (void*)类型指针:ANSI新增的:即定义了一个指针,但不指定指向任何类型(即指向抽象的数据类型). 1 通过强制类型转换可将其值赋给另一指针变量 2.1用于动态存储函数的返回型指针 void m ...

  10. 【PAT甲级】1061 Dating (20 分)

    题意: 给出四组字符串,前两串中第一个位置相同且大小相等的大写字母(A~G)代表了周几,前两串中第二个位置相同且大小相等的大写字母或者数字(0~9,A~N)代表了几点,后两串中第一个位置相同且大小相等 ...