概念
集成阿里云短信服务
引用阿里云包
封装AliyunSmsClient(二次封装阿里云短信基类)
public class AliyunSmsClient{private readonly Client _client;private readonly AliyunSmsOptions _options;public AliyunSmsClient(IOptions<AliyunSmsOptions> options){_options = options.Value;_client = new Client(new Config(){AccessKeyId = _options.AccessKeyId,AccessKeySecret = _options.AccessKeySecret,Endpoint = "dysmsapi.aliyuncs.com"});}public SendSmsResponse Send(SendSmsRequest req){if (!string.IsNullOrEmpty(_options.SignName))req.SignName = _options.SignName;return _client.SendSms(req);}public async Task<SendSmsResponse> SendAsync(SendSmsRequest req){if (!string.IsNullOrEmpty(_options.SignName))req.SignName = _options.SignName;return await _client.SendSmsAsync(req);}}
封装参数构造类AliyunSmsSendRequestBuilder
public class AliyunSmsSendRequestBuilder{private readonly SendSmsRequest _request;private readonly List<string> _phones;private readonly Dictionary<string, object> _templateParams;public AliyunSmsSendRequestBuilder(string templateCode){_request = new SendSmsRequest();_request.TemplateCode = templateCode;_phones = new List<string>();_templateParams = new Dictionary<string, object>();}public AliyunSmsSendRequestBuilder AddPhone(IEnumerable<string> phones) => AddPhone(phones.ToArray());public AliyunSmsSendRequestBuilder AddPhone(params string[] phones){_phones.AddRange(phones);return this;}public AliyunSmsSendRequestBuilder AddSignName( string signName){_request.SignName = signName;return this;} public AliyunSmsSendRequestBuilder AddTemplateParam(string key, object value){_templateParams.Add(key, value);return this;}public SendSmsRequest Build(){_request.PhoneNumbers = string.Join(",", _phones.Distinct());_request.TemplateParam = JsonConvert.SerializeObject(_templateParams as dynamic);return _request;}}
封装初始化参数类AliyunSmsOptions
public class AliyunSmsOptions{public string AccessKeyId { get; set; }public string AccessKeySecret { get; set; }public string SignName { get; set; }}
封装服务扩展静态类ServiceCollectionExtensions
public static class ServiceCollectionExtensions{public static IServiceCollection AddAliyunSms(this IServiceCollection services, Action<AliyunSmsOptions> setup){services.Configure(setup);services.AddSingleton<AliyunSmsClient>();return services;}}
.net6中使用
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAliyunSms((op) =>
{builder.Configuration.Bind("BPA:AliyunSms", op);
});
参数参考
"AliyunSms": {"AccessKeyId": "参考Key","AccessKeySecret": "参考Secret","SignName": "参考"},