- A+
所属分类:.NET技术
.NET CORE webapi 调用阿里云短信服务
1.获取AccessKey
您可以为阿里云账号(主账号)和RAM用户创建一个访问密钥(AccessKey)。在调用阿里云API时您需要使用AccessKey完成身份验证。
背景信息
AccessKey包括AccessKey ID和AccessKey Secret。
- AccessKey ID:用于标识用户。
- AccessKey Secret:用于验证用户的密钥。AccessKey Secret必须保密。
2.sdk文档
https://next.api.aliyun.com/api-tools/sdk/Dysmsapi?version=2017-05-25&language=csharp-tea
3.示例代码
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Tea;
using Tea.Utils;
namespace WebApplication1.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
[HttpGet("SendInfor")]
public IActionResult SendInfor(string phone)
{
AlibabaCloud.SDK.Dysmsapi20170525.Client client = Sample.CreateClient("LTAI5tSQ6zR2Y5YuaJWuVHpH", "Hfn9QCFHWd5abDNTxgPxS1fuKktMbs");
AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest sendSmsRequest = new AlibabaCloud.SDK.Dysmsapi20170525.Models.SendSmsRequest
{
SignName = "阿里云短信测试", //标题
TemplateCode = "SMS_154950909", //模板
PhoneNumbers = phone, //发送的手机号
TemplateParam = "{"code":"4321"}", //验证码信息
};
AlibabaCloud.TeaUtil.Models.RuntimeOptions runtime = new AlibabaCloud.TeaUtil.Models.RuntimeOptions();
try
{
// 复制代码运行请自行打印 API 的返回值
return Ok(client.SendSmsWithOptions(sendSmsRequest,runtime));
}
catch (TeaException error)
{
// 如有需要,请打印 error
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
return BadRequest(error.Message);
}
catch (Exception _error)
{
TeaException error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
// 如有需要,请打印 error
AlibabaCloud.TeaUtil.Common.AssertAsString(error.Message);
return BadRequest(_error.Message);
}
}
}
public static class Sample
{
/**
* 使用AK&SK初始化账号Client
* @param accessKeyId
* @param accessKeySecret
* @return Client
* @throws Exception
*/
public static AlibabaCloud.SDK.Dysmsapi20170525.Client CreateClient(string accessKeyId, string accessKeySecret)
{
AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config
{
// 您的AccessKey ID
AccessKeyId = accessKeyId,
// 您的AccessKey Secret
AccessKeySecret = accessKeySecret,
};
// 访问的域名
config.Endpoint = "dysmsapi.aliyuncs.com";
return new AlibabaCloud.SDK.Dysmsapi20170525.Client(config);
}
}
}
4.添加测试手机号 使用测试模板 收费是0.14一条 可以冲个五块钱试试
5.可以创建短信的模板 需要审核两个小时
6.调用结果