Skip to main content

Prerequisites

Before you begin:

  • A SpringEdge account and API key (sign up free; the key is shared after sign-up, along with test credits)
  • .NET 6 or higher (or .NET Framework 4.7.2+)
  • No NuGet packages: the built-in HttpClient and System.Text.Json are enough
  • A DLT-registered sender ID and an approved template (needed for every SMS sent in India)

Zero NuGet Dependencies

Built-in HttpClient, nothing to install

Async/Await

The request is awaited, so no thread sits blocked on the network

IHttpClientFactory

A typed client in ASP.NET Core, so connections are pooled and reused

// Program.cs (.NET 6+ console app)
using System.Text.Json;

const string ApiUrl = "https://web.springedge.com/api/web/send/";

// FormUrlEncodedContent URL-encodes each value
var form = new FormUrlEncodedContent(new Dictionary<string, string>
{
    ["apikey"]  = "YOUR_API_KEY",
    ["sender"]  = "SEDEMO",
    ["to"]      = "91XXXXXXXXXX",
    ["message"] = "Your OTP is 482910",
    ["format"]  = "json"
});

using var client = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };

try
{
    var response = await client.PostAsync(ApiUrl, form);
    var body = (await response.Content.ReadAsStringAsync()).Trim();

    if (response.IsSuccessStatusCode && TryGetMessageId(body, out var id))
    {
        Console.WriteLine($"Message ID: {id}");
        return 0;
    }

    // Errors come back as text, e.g. "Invalid Sender ID"
    Console.Error.WriteLine($"Not sent (HTTP {(int)response.StatusCode}): {body}");
    return 1;
}
catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
{
    // Network failure or timeout
    Console.Error.WriteLine($"Request failed: {ex.Message}");
    return 1;
}

// Accepted (format=json):
// {"groupID": 61, "MessageIDs": "61-1", "status": "AWAITED-DLR"}
static bool TryGetMessageId(string body, out string id)
{
    id = "";
    try
    {
        using var doc = JsonDocument.Parse(body);
        if (doc.RootElement.ValueKind == JsonValueKind.Object
            && doc.RootElement.TryGetProperty("MessageIDs", out var ids))
        {
            id = ids.ToString();
            return true;
        }
    }
    catch (JsonException)
    {
        // Not JSON: an error message as text
    }
    return false;
}

C# HttpClient

Basic C# Example

The program posts five form fields to the SpringEdge SMS API, with your key in apikey. FormUrlEncodedContent encodes the values, so spaces, & and Hindi text arrive intact. An accepted message returns JSON with a MessageIDs value; anything else is the API's reason in plain words, such as Insufficient Credits, and the program exits with code 1.

On .NET Framework 4.7.2+, put the same code in an async method, add the System.Text.Json NuGet package and reference System.Net.Http. All parameters are in the SMS API documentation.

Quick Start:

  1. dotnet new console -n SendSms
  2. Paste the code into Program.cs, then put in your API key, approved sender ID, a real mobile number and your DLT template text
  3. Run: dotnet run

ASP.NET CORE

ASP.NET Core Service

In ASP.NET Core, register SmsService as a typed client so IHttpClientFactory pools connections for you. Creating a new HttpClient for every SMS can exhaust sockets on a busy server.

Register in Program.cs:

builder.Services.AddHttpClient<SmsService>(c =>
    c.Timeout = TimeSpan.FromSeconds(30));

Keep SpringEdge:ApiKey in user secrets, environment variables or Key Vault rather than appsettings.json. Then inject the service and call var id = await _sms.SendAsync(phone, message);. It returns the message ID or throws with the API's reason.

// Services/SmsService.cs
using System.Text.Json;

public class SmsService
{
    private const string ApiUrl =
        "https://web.springedge.com/api/web/send/";
    private readonly HttpClient _http;
    private readonly string _apiKey;

    public SmsService(HttpClient http, IConfiguration config)
    {
        _http = http;
        _apiKey = config["SpringEdge:ApiKey"]
            ?? throw new InvalidOperationException(
                "SpringEdge:ApiKey is not configured");
    }

    /// <summary>Returns the message ID, e.g. "61-1".</summary>
    public async Task<string> SendAsync(
        string phone, string message,
        CancellationToken ct = default)
    {
        using var form = new FormUrlEncodedContent(
            new Dictionary<string, string>
            {
                ["apikey"]  = _apiKey,
                ["sender"]  = "SEDEMO",
                ["to"]      = phone,
                ["message"] = message,
                ["format"]  = "json"
            });

        using var resp = await _http.PostAsync(ApiUrl, form, ct);
        var body = (await resp.Content.ReadAsStringAsync(ct)).Trim();

        if (resp.IsSuccessStatusCode && body.StartsWith("{"))
        {
            using var doc = JsonDocument.Parse(body);
            if (doc.RootElement.TryGetProperty("MessageIDs", out var id))
            {
                return id.ToString();
            }
        }

        // e.g. "Insufficient Credits" or "Invalid Mobile Numbers"
        throw new InvalidOperationException($"SMS not sent: {body}");
    }
}

What You Can Build

OTP Verification

Plug SmsService into ASP.NET Core Identity's phone confirmation and two-factor login, so the code arrives by SMS.

Windows Service Alerts

Have a Windows Service or worker text the IT team when a disk fills up, a backup fails or a plant machine stops reporting.

Azure Functions

Send from a queue-triggered function so your web app drops a message on the queue and moves on; a timer trigger handles daily reminders.

ERP Integration

Let a .NET ERP or billing system text the customer when an invoice is raised, a payment is received or a due date is three days away.