阿里云短信服务与ASP.NET对接实例

发布于:2025-04-19 ⋅ 阅读:(17) ⋅ 点赞:(0)

准备工作

  1. 注册阿里云账号并开通阿里大于(现称"阿里云短信服务")服务

  2. 获取AccessKey ID和AccessKey Secret

  3. 申请短信签名和短信模板并审核通过

ASP.NET Web项目集成步骤

1. 安装阿里云SDK

通过NuGet包管理器安装阿里云短信服务SDK:

Install-Package Aliyun.Acs.Core
Install-Package Aliyun.Acs.Dysmsapi

2. 配置Web.config

<appSettings>节点中添加阿里云配置:

<add key="AliyunSMS_AccessKeyId" value="您的AccessKeyId"/>
<add key="AliyunSMS_AccessKeySecret" value="您的AccessKeySecret"/>
<add key="AliyunSMS_SignName" value="您的短信签名"/>
<add key="AliyunSMS_TemplateCode" value="您的模板CODE"/>

写其他位置也可以。

3. 创建短信服务帮助类

using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using System;
using System.Web.Configuration;

public class AliyunSMSHelper
{
    private static string accessKeyId = WebConfigurationManager.AppSettings["AliyunSMS_AccessKeyId"];
    private static string accessKeySecret = WebConfigurationManager.AppSettings["AliyunSMS_AccessKeySecret"];
    private static string signName = WebConfigurationManager.AppSettings["AliyunSMS_SignName"];
    private static string templateCode = WebConfigurationManager.AppSettings["AliyunSMS_TemplateCode"];

    public static SendSmsResponse SendSms(string phoneNumbers, string templateParam)
    {
        // 设置超时时间
        System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
        
        IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", "dysmsapi.aliyuncs.com");
        IAcsClient acsClient = new DefaultAcsClient(profile);
        SendSmsRequest request = new SendSmsRequest();
        
        try
        {
            // 必填:待发送手机号
            request.PhoneNumbers = phoneNumbers;
            // 必填:短信签名
            request.SignName = signName;
            // 必填:短信模板Code
            request.TemplateCode = templateCode;
            // 可选:模板中的变量替换JSON串
            request.TemplateParam = templateParam;
            
            SendSmsResponse response = acsClient.GetAcsResponse(request);
            return response;
        }
        catch (Exception ex)
        {
            // 记录日志
            System.Diagnostics.Trace.WriteLine($"短信发送异常: {ex.Message}");
            return null;
        }
    }
}

4. 在控制器中使用短信服务

using System.Web.Mvc;

public class SmsController : Controller
{
    public ActionResult SendVerificationCode(string phoneNumber)
    {
        // 生成随机验证码
        string code = new Random().Next(1000, 9999).ToString();
        
        // 模板参数JSON (根据实际模板参数调整)
        string templateParam = $"{{\"code\":\"{code}\"}}";
        
        // 发送短信
        var response = AliyunSMSHelper.SendSms(phoneNumber, templateParam);
        
        if (response != null && response.Code == "OK")
        {
            // 发送成功,将验证码存入Session或数据库
            Session["VerificationCode"] = code;
            Session["VerificationPhone"] = phoneNumber;
            
            return Json(new { success = true, message = "验证码发送成功" });
        }
        else
        {
            string errorMsg = response?.Message ?? "短信服务异常";
            return Json(new { success = false, message = $"验证码发送失败: {errorMsg}" });
        }
    }
    
    public ActionResult VerifyCode(string phoneNumber, string code)
    {
        if (Session["VerificationPhone"]?.ToString() == phoneNumber && 
            Session["VerificationCode"]?.ToString() == code)
        {
            // 验证成功
            return Json(new { success = true, message = "验证码正确" });
        }
        
        return Json(new { success = false, message = "验证码错误或已过期" });
    }
}

5. 前端调用示例 (jQuery)

// 发送验证码
$("#btnSendCode").click(function() {
    var phone = $("#phoneNumber").val();
    if (!phone) {
        alert("请输入手机号码");
        return;
    }
    
    $.post("/Sms/SendVerificationCode", { phoneNumber: phone }, function(data) {
        if (data.success) {
            alert("验证码已发送");
            // 开始倒计时
            countDown(60);
        } else {
            alert(data.message);
        }
    });
});

// 验证验证码
$("#btnVerify").click(function() {
    var phone = $("#phoneNumber").val();
    var code = $("#verificationCode").val();
    
    $.post("/Sms/VerifyCode", { phoneNumber: phone, code: code }, function(data) {
        alert(data.message);
        if (data.success) {
            // 验证成功后的操作
        }
    });
});

// 倒计时函数
function countDown(seconds) {
    var btn = $("#btnSendCode");
    btn.attr("disabled", true);
    
    var timer = setInterval(function() {
        btn.val(seconds + "秒后重新发送");
        seconds--;
        
        if (seconds <= 0) {
            clearInterval(timer);
            btn.val("获取验证码");
            btn.attr("disabled", false);
        }
    }, 1000);
}

注意事项

  1. 短信签名和模板需要先在阿里云控制台申请并通过审核

  2. 生产环境建议将验证码存储在服务器端(如Session、Redis等)并设置有效期

  3. 对短信发送频率进行限制,防止恶意刷短信

  4. 敏感信息如AccessKey不要直接暴露在前端代码中

  5. 建议添加IP限制、图形验证码等安全措施

  6. 处理短信发送失败的情况,提供友好的用户提示

以上是一个基本的阿里大于(阿里云短信服务)与ASP.NET Web项目的对接实例,您可以根据实际需求进行调整和扩展。


网站公告

今日签到

点亮在社区的每一天
去签到