.net core webapi 使用短息模板dome
const String product = "Dysmsapi"; //產品域名,開發者無需替換 const String domain = "dysmsapi.aliyuncs.com";
// TODO 此處需要替換成開發者自己的AK(在阿里雲訪問控制檯尋找) const String accessKeyId = "LTAIF7R4BvL9hVV0"; const String accessKeySecret = "uAWf4dIXny3sRZ923zzqWYTHX0icII";
下面是方法
/// <summary> /// 短息介面 /// </summary> /// <param name="mobile"></param> /// <param name="factory"></param> /// <param name="user"></param> /// <returns></returns>
[HttpPost("api/SendSMSController/sendsms")] public SendSmsResponse SendSms(string mobile, string factory, string user) { IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret); DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); IAcsClient acsClient = new DefaultAcsClient(profile); SendSmsRequest request = new SendSmsRequest(); SendSmsResponse response = new SendSmsResponse ();
//生成 驗證碼 Random rd = new Random(); int num = rd.Next(100000, 1000000); try {
//必填:待發送手機號。支援以逗號分隔的形式進行批量呼叫,批量上限為1000個手機號碼,批量呼叫相對於單條呼叫及時性稍有延遲,驗證碼型別的簡訊推薦使用單條呼叫的方式 request.PhoneNumbers = mobile; //手機號 //必填:簡訊簽名-可在簡訊控制檯中找到 request.SignName = "短息名稱自定義
//${factory}的${user},電話${mobile},正在操作物權轉移一批車輛給您,驗證碼是${code},請收到驗證碼後與${factory}相關人員核實! //${factory}的${user}正在操作轉移一批車輛給您,提醒碼是${text},請與相關人員核實!
//通過模板設定引數
var msg = new { factory = factory, user = user, mobile = mobile, text = num }; var jsdata = JsonConvert.SerializeObject(msg);
CaptchaBll.Add(num.ToString(), mobile,20);//存入資料庫驗證碼錶
request.TemplateParam = jsdata; //可選:outId為提供給業務方擴充套件欄位,最終在簡訊回執訊息中將此值帶回給呼叫者 request.OutId = "yourOutId"; //請求失敗這裡會拋ClientException異常 response = acsClient.GetAcsResponse(request);
} catch (ServerException e) { Console.WriteLine(e.ErrorCode); } catch (ClientException e) { Console.WriteLine(e.ErrorCode); } return response;
}