简介
现在只要是应用,一般都会用到发送短信这个功能,非常普遍,那么今天就来讲一下如何使用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,欢迎关注