在ASP.NET中实现短信发送功能,通常需要借助第三方的短信服务提供商,以下是使用互亿无线和阿里云短信服务的详细步骤和示例代码:
1、注册账号:前往互亿无线官网(http://user.ihuyi.com/?t9nyDN)注册一个账号,注册完成后会获得10条免费短信以及通话验证码。
2、创建SendSmsUtil类:在项目中创建一个名为SendSmsUtil.cs
的类文件,用于封装发送短信的逻辑。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
public class SendSmsUtil
{
private static readonly string URL = "http://106.ihuyi.com/webservice/sms.php?method=Submit"; // 国内请求路径
private static readonly string APPID = "这里填写自己的APPID"; // 这里填写自己的APPID
private static readonly string APIKEY = "这里填写自己的APIKEY"; // 这里填写自己的APIKEY
public static async Task<string> SendSmsAsync(string number)
{
using (var client = new HttpClient())
{
// 随机生成六位数的验证码
Random random = new Random();
int mobileCode = random.Next(100000, 999999);
string content = $"您的验证码是:{mobileCode},请不要把验证码泄露给其他人。";
var parameters = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("account", APPID),
new KeyValuePair<string, string>("password", APIKEY),
new KeyValuePair<string, string>("mobile", number),
new KeyValuePair<string, string>("content", content)
};
var contentToSend = new FormUrlEncodedContent(parameters);
try
{
var response = await client.PostAsync(URL, contentToSend);
var responseBody = await response.Content.ReadAsStringAsync();
// 解析XML响应
XDocument xmlDoc = XDocument.Parse(responseBody);
// 从XML中获取信息
var code = xmlDoc.Root.Element(XName.Get("code", "http://106.ihuyi.com/"))?.Value;
var msg = xmlDoc.Root.Element(XName.Get("msg", "http://106.ihuyi.com/"))?.Value;
var smsid = xmlDoc.Root.Element(XName.Get("smsid", "http://106.ihuyi.com/"))?.Value;
Console.WriteLine($"code: {code}");
Console.WriteLine($"msg: {msg}");
Console.WriteLine($"smsid: {smsid}");
Console.WriteLine($"mo: {mobileCode}");
if (code == "2")
{
Console.WriteLine("短信提交成功");
return mobileCode.ToString();
}
}
catch (Exception ex)
{
Console.WriteLine($"发送短信时发生错误: {ex.Message}");
}
}
return "";
}
}
3、在控制器中使用SendSmsUtil类:在ASP.NET Core的控制器中,可以通过调用SendSmsUtil
类的SendSmsAsync
方法来发送短信,在一个名为SmsController
的控制器中添加一个SendSms
动作方法。
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
[ApiController]
[Route("api/[controller]")]
public class SmsController : ControllerBase
{
[HttpPost("send")]
public async Task<IActionResult> SendSms([FromBody] string phoneNumber)
{
var result = await SendSmsUtil.SendSmsAsync(phoneNumber);
if (!string.IsNullOrEmpty(result))
{
return Ok(new { message = "短信发送成功", code = result });
}
else
{
return StatusCode(500, new { message = "短信发送失败" });
}
}
}
1、环境准备:注册阿里云账号,并开通短信服务;创建短信模板,并获取模板的ID和签名;获取阿里云API的Access Key和Secret,用于身份验证;安装阿里云SDK,在项目的appsettings.json文件中添加配置项。
{
"AliyunSms": {
"AccessKeyId": "YourAccessKeyId",
"AccessKeySecret": "YourAccessKeySecret",
"SignName": "YourSignName"
}
}
2、编写短信发送代码:在.NET Core应用程序中,可以使用阿里云SDK提供的SendSmsRequest
类来向用户发送短信。
using Aliyun.SDK.SMS;
using Microsoft.Extensions.Configuration;
using System;
using System.Threading.Tasks;
public class AliyunSmsService
{
private readonly IConfiguration _configuration;
private readonly ISMSClient _smsClient;
public AliyunSmsService(IConfiguration configuration)
{
_configuration = configuration;
var accessKeyId = _configuration["AliyunSms:AccessKeyId"];
var accessKeySecret = _configuration["AliyunSms:AccessKeySecret"];
_smsClient = SMSClient.Create(accessKeyId, accessKeySecret);
}
public async Task<bool> SendSmsAsync(string phoneNumber, string templateParam)
{
var request = new SendSmsRequest
{
PhoneNumbers = phoneNumber,
SignName = _configuration["AliyunSms:SignName"],
TemplateCode = "YourTemplateCode", // 替换为你的模板ID
TemplateParam = templateParam
};
var response = await _smsClient.SendSmsAsync(request);
if (response.IsSuccess)
{
Console.WriteLine("短信发送成功!");
return true;
}
else
{
Console.WriteLine($"短信发送失败:{response.Message}");
return false;
}
}
}
3、在控制器中使用AliyunSmsService类:在控制器中注入AliyunSmsService
类,并调用其SendSmsAsync
方法来发送短信。
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
[ApiController]
[Route("api/[controller]")]
public class SmsController : ControllerBase
{
private readonly AliyunSmsService _aliyunSmsService;
public SmsController(IConfiguration configuration)
{
_aliyunSmsService = new AliyunSmsService(configuration);
}
[HttpPost("send")]
public async Task<IActionResult> SendSms([FromBody] SmsRequest request)
{
var result = await _aliyunSmsService.SendSmsAsync(request.PhoneNumber, request.TemplateParam);
if (result)
{
return Ok(new { message = "短信发送成功" });
}
else
{
return StatusCode(500, new { message = "短信发送失败" });
}
}
}
public class SmsRequest
{
public string PhoneNumber { get; set; }
public string TemplateParam { get; set; }
}
1、问:如何在ASP.NET中选择合适的短信服务提供商?
答:在选择短信服务提供商时,可以考虑以下因素:价格、服务质量(包括短信送达率、发送速度等)、接口文档的完整性和易用性、提供商的信誉和口碑、是否提供技术支持等,还可以参考其他开发者的使用经验和评价,以便做出更合适的选择。
2、问:在使用短信服务时,如何确保用户信息安全?
答:为了确保用户信息安全,可以采取以下措施:对用户的手机号码进行加密存储和传输,避免明文显示;在发送短信时,不要在短信内容中包含敏感信息;定期更新短信服务提供商的账号密码和访问密钥,防止账号被盗用;限制短信发送的频率和数量,防止反面刷短信等情况的发生。