C# ASP.NET Core Web API 框架 实现向手机发送验证码短信

C# ASP.NET Core Web API 框架 实现向手机发送验证码短信 实现向手机发送验证码短信 ASP. Core NET Web API ASP 框架 C#

本文章主要是在C# ASP.NET Core Web API框架实现向手机发送验证码短信功能。这里我选择是一个互亿无线短信验证码平台,其实像阿里云,腾讯云上面也可以

  1. 首先我们先去 互亿无线 https://www.ihuyi.com/api/sms.html 去注册一个账号
    注册完成账号后,它会送10条免费短信以及通话验证码(ps:我这上面不是10条因为我已经使用了 新人都是10条)
    2.下面开始代码首先创建一个SendSmsUtil.cs的类


3.下面直接上代码
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace YourNamespace.Utils
{
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 响应
                // 解析 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 "";
        }
    }
}

}

4.APPID和APIKEY 在这个地方查看
5.下面是控制器中需要的代码
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using YourNamespace.Utils;

namespace YourNamespace.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SmsController : ControllerBase
{
[HttpPost("send")]
public async Task SendSms([FromBody] string phoneNumber)
{
if (string.IsNullOrEmpty(phoneNumber))
{
return BadRequest("手机号码不能为空");
}

        var result = await SendSmsUtil.SendSmsAsync(phoneNumber);
        if (string.IsNullOrEmpty(result))
        {
            return StatusCode(500, "发送短信失败");
        }

        return Ok(new { VerificationCode = result });
    }
}

}

6.输入手机号并且测试 下面是个成功的结果 手机并且能受到验证码

以上内容已实现手机验证码功能。代码主要参考官网代码和AI生成还有,可能存在一些语句问题感谢大家的指导和建议!
转载请请注明出处,谢谢!
朱世杰(@Twolp)指导

评论