Quick answer
To use an OTP SMS API in .NET, generate a 6-digit code on your server with RandomNumberGenerator.GetInt32, store only a hash of it with a 5-minute expiry, and send it with one HTTPS GET to the SMSGatewayHub SendSMS endpoint (channel=OTP) through IHttpClientFactory. When the user types the code, your ASP.NET Core endpoint compares it with the stored hash, limits attempts and deletes it after one use. OTP SMS costs ₹0.185 to ₹0.245 per SMS + 18% GST, with typical delivery in 2-6 seconds.
Key takeaways
- Your server owns the code. The API delivers the SMS; your ASP.NET Core app generates, stores and verifies the OTP. Nothing is verified on our side.
- Use the right primitives:
RandomNumberGenerator.GetInt32 for the code, IHttpClientFactory for the call, IMemoryCache or Redis for short-lived storage.
- Protect the flow: hash the code, expire it in 5 minutes, allow 5 attempts, and rate-limit send requests with the built-in rate limiter in .NET 7 and later.
- DLT is mandatory in India: every request carries your entity ID and approved OTP template ID, and the text must match the template.
What do you need before you start?
Before you write any C#, collect four values from your SMSGatewayHub panel and your DLT registration. Without them the request is rejected or the message fails DLT scrubbing at the operator.
| Value | Where you get it | Request parameter |
| API key | Your SMSGatewayHub panel after you create a free account | APIKey |
| Sender ID (header) | Your transactional header registered on DLT | senderid |
| DLT entity ID | Your principal entity registration | EntityId |
| OTP template ID | Your approved OTP template on DLT | dlttemplateid |
If you have not finished DLT yet, our team helps with DLT registration free of cost. The full parameter list is in the developer API docs.
How does the OTP flow work in an ASP.NET Core app?
- The user enters a mobile number in your web or mobile app, which calls
POST /otp/send on your ASP.NET Core API.
- Your API generates a 6-digit code, stores its hash with an expiry and an attempt counter, and calls SendSMS.
- SMSGatewayHub delivers the SMS on a transactional OTP route, with automatic retry and load balancing across operator routes.
- The user types the code and your app calls
POST /otp/verify.
- Your API compares hashes, checks expiry and attempts, then deletes the entry so the code works once only.
How do you send the OTP with HttpClient in C#?
Register a named or typed client with IHttpClientFactory so sockets are reused correctly, and keep the API key in configuration, never in source code. The service below generates the code, stores the hash and sends the SMS.
// appsettings.json (store the key in user-secrets or an environment variable in production)
// "SmsGatewayHub": { "ApiKey": "", "SenderId": "ABCDEF", "EntityId": "", "TemplateId": "" }
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Caching.Memory;
public sealed record OtpEntry(string Hash, DateTimeOffset Expires, int Attempts);
public sealed class OtpService
{
private readonly HttpClient _http;
private readonly IMemoryCache _cache;
private readonly IConfiguration _cfg;
public OtpService(HttpClient http, IMemoryCache cache, IConfiguration cfg)
{ _http = http; _cache = cache; _cfg = cfg; }
private static string Hash(string phone, string code) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(phone + ":" + code)));
public async Task<bool> SendAsync(string phone, CancellationToken ct)
{
string code = RandomNumberGenerator.GetInt32(100000, 1000000).ToString();
_cache.Set("otp:" + phone, new OtpEntry(Hash(phone, code), DateTimeOffset.UtcNow.AddMinutes(5), 0),
TimeSpan.FromMinutes(5));
var s = _cfg.GetSection("SmsGatewayHub");
var q = new Dictionary<string, string>
{
["APIKey"] = s["ApiKey"]!, ["senderid"] = s["SenderId"]!, ["channel"] = "OTP",
["DCS"] = "0", ["flashsms"] = "0", ["number"] = phone, ["route"] = "1",
["text"] = $"{code} is your OTP to log in to ABC App. Do not share it. - ABC",
["EntityId"] = s["EntityId"]!, ["dlttemplateid"] = s["TemplateId"]!
};
string url = "https://www.smsgatewayhub.com/api/mt/SendSMS?" +
string.Join("&", q.Select(kv => kv.Key + "=" + Uri.EscapeDataString(kv.Value)));
using var res = await _http.GetAsync(url, ct);
using var doc = JsonDocument.Parse(await res.Content.ReadAsStringAsync(ct));
string err = doc.RootElement.GetProperty("ErrorCode").GetString() ?? "";
return err == "000"; // 000 = accepted; log JobId for delivery reports
}
}
Register the pieces in Program.cs:
builder.Services.AddMemoryCache();
builder.Services.AddHttpClient<OtpService>(c => c.Timeout = TimeSpan.FromSeconds(10));
ℹ️The text must match your approved DLT template exactly, with the code in the {#numeric#} variable. If one word differs, the operator blocks the message even though the API accepted it.
What does the API response look like?
A successful request returns JSON like this. ErrorCode "000" means the OTP was accepted for delivery.
{ "ErrorCode": "000", "ErrorMessage": "Success", "JobId": "20047",
"MessageData": [ { "Number": "9198XXXXXXXX", "MessageId": "..." } ] }
Store the JobId and MessageId with the login attempt. You can then match them with the live delivery reports to see whether the code reached the phone, and decide whether to offer a resend or another channel. Any other error code comes with an ErrorMessage; log it and show the user a simple "try again" message.
How do you build send and verify endpoints with a minimal API?
Two small endpoints are enough. The verify endpoint never returns the code and gives the same answer for a wrong code and an expired code, so attackers learn nothing.
app.MapPost("/otp/send", async (SendReq r, OtpService otp, CancellationToken ct) =>
{
if (!System.Text.RegularExpressions.Regex.IsMatch(r.Phone ?? "", @"^91[6-9]\d{9}$"))
return Results.BadRequest(new { error = "Enter a valid Indian mobile number." });
bool ok = await otp.SendAsync(r.Phone!, ct);
return ok ? Results.Ok(new { sent = true }) : Results.StatusCode(502);
}).RequireRateLimiting("otp-send");
app.MapPost("/otp/verify", (VerifyReq r, IMemoryCache cache) =>
{
string key = "otp:" + r.Phone;
if (!cache.TryGetValue(key, out OtpEntry? e) || e is null || e.Expires < DateTimeOffset.UtcNow)
return Results.Ok(new { verified = false });
if (e.Attempts >= 5) { cache.Remove(key); return Results.Ok(new { verified = false }); }
byte[] a = Convert.FromHexString(e.Hash);
byte[] b = SHA256.HashData(Encoding.UTF8.GetBytes(r.Phone + ":" + r.Code));
if (!CryptographicOperations.FixedTimeEquals(a, b))
{
cache.Set(key, e with { Attempts = e.Attempts + 1 }, e.Expires);
return Results.Ok(new { verified = false });
}
cache.Remove(key); // one use only
return Results.Ok(new { verified = true });
});
public record SendReq(string? Phone);
public record VerifyReq(string? Phone, string? Code);
✔CryptographicOperations.FixedTimeEquals compares the hashes in constant time, so response timing does not leak how many digits matched.
How do you rate-limit OTP requests in .NET 7 and later?
OTP endpoints are a favourite target for SMS pumping, where bots trigger thousands of paid messages. ASP.NET Core ships a rate limiter in Microsoft.AspNetCore.RateLimiting. Partition it by phone number or client IP:
using System.Threading.RateLimiting;
builder.Services.AddRateLimiter(o =>
{
o.RejectionStatusCode = 429;
o.AddPolicy("otp-send", ctx =>
RateLimitPartition.GetFixedWindowLimiter(
ctx.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions { PermitLimit = 3, Window = TimeSpan.FromMinutes(10) }));
});
// ...
app.UseRateLimiter();
Also enforce a per-number cooldown of 30 to 60 seconds between sends and a daily cap per number. The full resend logic, with a new code every time, is covered in our guide to verify OTP and resend OTP.
Should you use IMemoryCache or Redis for OTP codes?
| Store | Good for | Watch out for |
| IMemoryCache | One server, simple apps, prototypes | Codes are lost on restart and are not shared across servers |
| IDistributedCache with Redis | Load-balanced apps, containers, Kubernetes | Set an absolute expiry on every entry; serialize the record as JSON |
| SQL table | Audit needs, existing database only | Clean up expired rows with a scheduled job |
If your app runs on more than one instance, switch to IDistributedCache (for example AddStackExchangeRedisCache) so a code sent by one server can be verified by another.
What about .NET Framework and ASP.NET WebForms?
Older apps on .NET Framework 4.7.2 or 4.8 can use the same API. Create one static HttpClient for the whole app (do not create one per request), generate the code with RNGCryptoServiceProvider or RandomNumberGenerator.Create(), and keep the hash in HttpRuntime.Cache with an absolute expiry of five minutes. Make sure TLS 1.2 is enabled with ServicePointManager.SecurityProtocol on very old builds. The flow, the parameters and the response are exactly the same.
Why do .NET teams choose the SMSGatewayHub OTP SMS API?
- Fast OTP delivery: 2-6 seconds typical, with automatic retry and load balancing across operator routes.
- Clear pricing: ₹0.185 to ₹0.245 per OTP SMS + 18% GST, DLT scrubbing included, and you pay only for delivered SMS. See OTP SMS pricing.
- Reliable platform: 99.9% uptime SLA, ISO 27001 certified, serving businesses since 2009.
- Free DLT help: we help register your entity, header and OTP templates.
- No-code option: if you do not want users to type a code, try OneTap Verify login links.
Get 1,000 free SMS credits and send your first OTP from C#
No credit card. Free DLT registration help. Your API key is ready in minutes.
Create free account
Frequently asked questions
How do I send an OTP SMS from ASP.NET Core?
Generate the code with RandomNumberGenerator.GetInt32, store its hash with a 5-minute expiry, and call the SendSMS endpoint with HttpClient from IHttpClientFactory, passing channel=OTP, your sender ID, DLT entity ID and OTP template ID. ErrorCode 000 in the JSON response means the OTP was accepted.
Does SMSGatewayHub verify the OTP for my .NET app?
No. Your ASP.NET Core API generates and verifies the code, so the OTP never leaves your system. SMSGatewayHub delivers the SMS and gives you delivery reports.
Which C# method should I use to generate an OTP?
Use System.Security.Cryptography.RandomNumberGenerator.GetInt32(100000, 1000000). Do not use System.Random, because its output can be predicted.
How much does the OTP SMS API cost?
OTP SMS costs ₹0.185 to ₹0.245 per SMS plus 18% GST depending on pack size, with the DLT scrubbing charge included. You pay only for delivered OTPs, and new accounts get 1,000 free SMS credits.
Can I use the same API from .NET Framework or WebForms?
Yes. Any .NET version that can make an HTTPS GET request can send OTPs. Use one shared HttpClient, enable TLS 1.2 and keep the hashed code in HttpRuntime.Cache with a short expiry.
Related reading: OTP SMS API, OTP REST API reference, verify and resend OTP, OTP SMS API in Java and Android, and testing your OTP API in Postman.
Sources: SMSGatewayHub OTP SMS API documentation and published OTP pricing (November 2026); Microsoft documentation for RandomNumberGenerator, IHttpClientFactory, IMemoryCache and ASP.NET Core rate limiting; TRAI DLT rules for commercial SMS. Prices exclude 18% GST and can change; confirm your rate with sales.