簡介
現在只要是應用,一般都會用到發送短信這個功能,非常普遍,那麼今天就來講一下如何使用NCF寫發送短信接口
參考文檔
開發文檔:https://help.aliyun.com/document_detail/101414.html?spm=a2c4g.11186623.6.628.53d14fe8pYm0tR
NCF倉庫地址:https://github.com/NeuCharFramework/NCF (要Star哦)
步驟
1.下載NCF
2.創建自己的XNCF模塊
3.引用Nuget包AlibabaCloud.SDK.Dysmsapi20170525
4.建立自己的Controller,並創建方法,調用發送短信方法
5.建立調用短信的類,創建發送短信方法
案例
1.直接到Github上下載NCF的源碼master分支
2.請參考NCF開發文檔中的創建XNCF模塊
3.項目中引入
1 <ItemGroup> 2 <PackageReference Include="AlibabaCloud.SDK.Dysmsapi20170525" Version="1.0.2" /> 3 </ItemGroup>
4.建立自己的Controller,並創建方法,調用發送短信方法
1 /// <summary> 2 /// 發送短信驗證碼 3 /// </summary> 4 /// <param name="mobile">手機號</param> 6 /// <returns></returns> 7 [HttpGet] 8 public async Task<IActionResult> SendSMS(string mobile) 9 { 10 try 11 { 12 var response = await ApiSendCodeAsync(mobile); 13 return Success(response); 14 } 15 catch (Exception ex) 16 { 17 return Fail(ex.Message); 18 } 19 }
5.建立調用短信的類,創建發送短信方法
1 using AlibabaCloud.SDK.Dysmsapi20170525; 2 using AlibabaCloud.SDK.Dysmsapi20170525.Models; 3 using AlibabaCloud.OpenApiClient.Models;
1 public async Task<object> ApiSendCodeAsync(string mobile) 2 { 3 Random random = new Random(); 4 string strCode = random.Next(100000, 999999).ToString(); 5 string strTemplateCode = "SMS_000000000"; 6 string accessKeyId = "LTAI*********LB4"; 7 string accessKeySecret = "vp**************************BW"; 8 Config config = new Config 9 { 10 // 您的AccessKey ID 11 AccessKeyId = accessKeyId, 12 // 您的AccessKey Secret 13 AccessKeySecret = accessKeySecret, 14 }; 15 // 訪問的域名 16 config.Endpoint = "dysmsapi.aliyuncs.com"; 17 Client client = new Client(config); 18 SendSmsRequest sendSmsRequest = new SendSmsRequest 19 { 20 PhoneNumbers = mobile, 21 SignName = "米立科技", 22 TemplateCode = strTemplateCode, 23 TemplateParam = $"{{\"code\":\"{strCode}\"}}", 24 }; 25 // 複製代碼運行請自行打印 API 的返回值 26 var smsResponse = client.SendSms(sendSmsRequest); 27 // 將驗證碼寫入Redis 28 SenparcRedis.Set($"VerificationCode:{mobile}", strCode, 300); 29 return strCode; 30 }
結語
按照上面的方法讓你瞬間解決發送短信的難題,歡迎大家交流,歡迎Star,歡迎關注