使用 C# (.NET) 发送短信:集成短信服务 API
在现代世界中,发送短信仍然是通知、双因素身份验证和客户提醒的常见需求。在 .NET 生态系统中,没有内置的短信发送库——所有操作都是通过向第三方短信提供商的 API 发送 HTTP 请求来完成的。在本文中,我们将探讨如何使用 HttpClient 在 C# 中组织短信发送,并介绍与流行服务集成的示例。
选择短信提供商和关键参数
在开始之前,您需要注册一个短信服务。最流行的包括:Twilio、Vonage (Nexmo)、SMS Aero、СМСЦентр。它们都提供 REST API。发送短信需要以下信息:
- API 密钥 / 令牌 — 您账户的唯一标识符。
- Secret / 密码 — 用于身份验证的密钥。
- 发送者号码 (Sender ID) — 将显示在接收者设备上的字符串(例如,您的品牌名称)。
- 接收者号码 — 国际格式(例如,+71234567890)。
使用 HttpClient 的 C# 基本实现
在 .NET 中,使用 System.Net.Http.HttpClient 类处理 HTTP 请求。以下是通过 Twilio API(最流行的服务之一)发送短信的示例。
using System;using System.Net.Http;using System.Text;using System.Threading.Tasks;
public class SmsSender{ private readonly HttpClient _httpClient; private readonly string _accountSid; private readonly string _authToken;
public SmsSender(string accountSid, string authToken) { _accountSid = accountSid; _authToken = authToken; _httpClient = new HttpClient(); }
public async Task SendSmsAsync(string to, string from, string message) { // Twilio API 的 URL string url = $"https://api.twilio.com/2010-04-01/Accounts/{_accountSid}/Messages.json";
// 构建表单数据 var content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("To", to), new KeyValuePair<string, string>("From", from), new KeyValuePair<string, string>("Body", message) });
// 添加基本身份验证 string auth = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{_accountSid}:{_authToken}")); _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", auth);
// 发送 POST 请求 HttpResponseMessage response = await _httpClient.PostAsync(url, content);
if (response.IsSuccessStatusCode) { string responseBody = await response.Content.ReadAsStringAsync(); Console.WriteLine($"短信发送成功: {responseBody}"); } else { string error = await response.Content.ReadAsStringAsync(); Console.WriteLine($"错误: {response.StatusCode} - {error}"); } }}使用该类
class Program{ static async Task Main(string[] args) { // 替换为您的 Twilio 账户信息 string accountSid = "ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; string authToken = "your_auth_token_here";
var sender = new SmsSender(accountSid, authToken); await sender.SendSmsAsync( to: "+71234567890", from: "+15017122661", // Twilio 分配的号码 message: "你好!这是来自 C# 的测试短信。" ); }}其他提供商:以 Vonage (Nexmo) 为例
对于 Vonage API,使用不同的格式