版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/SunshineBlog/article/details/83659284
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using System.Security.Cryptography;//md5需要引入的命名空间
namespace WebApplication1.Controllers
{
public class SendMessagesController : Controller
{
// GET: SendMessages
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult SendMessages(string tel)
{
string accountSid = "";//开发者主账号ID(ACCOUNT SID)
string token = "";//开发者token
string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");//时间戳 yyyyMMddHHmmss 5分钟内有效
//随机生成验证码
Random rd = new Random();
string num = rd.Next(1000, 10000).ToString();
//模仿浏览器访问:
HttpClient hc = new HttpClient();
List<KeyValuePair<string, string>> keylist = new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("accountSid",accountSid),
//new KeyValuePair<string, string>("smsContent",""),// 短信内容。(smsContent与templateid必须填写一项)
new KeyValuePair<string, string>("templateid","89356984"),//短信模板ID
new KeyValuePair<string, string>("param",num+",5"),//短信变量 可选
new KeyValuePair<string, string>("to",tel),//收端手机号码集合。用英文逗号分开
new KeyValuePair<string, string>("timestamp",timestamp),
new KeyValuePair<string, string>("sig",Md5(accountSid+token+timestamp).ToLower()),//MD5(ACCOUNT SID + AUTH TOKEN + timestamp)小写
new KeyValuePair<string, string>("respDataType","JSON"),//可选,默认为json 可以为xml
};
//请求参数
HttpContent hct = new FormUrlEncodedContent(keylist);
HttpResponseMessage hrm = hc.PostAsync("https://api.miaodiyun.com/20150822/industrySMS/sendSMS", hct).Result;
return Json(hrm.Content.ReadAsStringAsync().Result);
}
/// <summary>
/// md5加密
/// </summary>
/// <param name="str">要加密的内容</param>
/// <returns></returns>
public static string Md5(string str)
{
//把字符串转化为字节数组
byte[] before_bytestr = System.Text.Encoding.Default.GetBytes(str);
MD5 md5 = new MD5CryptoServiceProvider();
//通过字节数组转化为加密后的字节数组(hash编码值)
byte[] after_bytestr = md5.ComputeHash(before_bytestr);
//加密后的字节数组转化成字符串
string md5str = BitConverter.ToString(after_bytestr).Replace("-", "");
return md5str;
}
}
}
@{
ViewBag.Title = "Index";
}
<link href="~/Content/layer/mobile/need/layer.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Content/layer/layer.js"></script>
<script>
$(function () {
$("#btnSend").click(function () {
$.post("SendMessages/SendMessages", { tel: $("#tel").val() }, function (res) {
var result = JSON.parse(res);
layer.open({
title: "温馨提示",
content: result.respDesc,
btn: ["确认"],
btn1: function () {
layer.closeAll();
}
});
});
});
});
</script>
<br /><br /><input type="text" name="tel" id="tel" value="" /><br /><br />
<input type="button" id="btnSend" value="获取验证码" /><br /><br />