Integrations
Validate phone numbers and emails in ASP.NET Core
Add a typed HttpClient and a minimal API endpoint in ASP.NET Core that check emails, phone numbers and IPs, reject bad input with a 422 and fail open on API errors.
Updated 2026-11-23
This recipe adds a typed client and a minimal API signup endpoint to an ASP.NET Core app. Clear negatives answer 422 with the field errors, and an API outage never blocks a signup. The C# and .NET recipe covers the same calls outside ASP.NET Core.
What you need
- .NET 8 or later.
- A Qelka API key in configuration as
Validate:ApiKey(environment variableValidate__ApiKey). Ask_test_key returns simulated results and never spends credits: see Test mode. - Server-side code only: see Authentication.
Steps
1. The typed client
using System.Net;
using System.Net.Http.Json;
using System.Text.Json.Nodes;
namespace App.Validation;
public sealed class ApiFailure(int status, string type, string? requestId) : Exception(type)
{
public int Status { get; } = status;
public string Type { get; } = type;
public string? RequestId { get; } = requestId;
}
public sealed class ValidateClient(HttpClient http)
{
private static readonly HashSet<HttpStatusCode> Retryable =
[HttpStatusCode.TooManyRequests, HttpStatusCode.InternalServerError, HttpStatusCode.BadGateway, HttpStatusCode.ServiceUnavailable];
private async Task<JsonNode> CallAsync(string path, object body, CancellationToken cancellation)
{
for (var attempt = 1; ; attempt++)
{
using var response = await http.PostAsJsonAsync(path, body, cancellation);
var json = await response.Content.ReadFromJsonAsync<JsonNode>(cancellation);
if (response.IsSuccessStatusCode && json is not null)
{
return json;
}
var requestId = response.Headers.TryGetValues("X-Request-Id", out var ids) ? ids.FirstOrDefault() : null;
if (!Retryable.Contains(response.StatusCode) || attempt == 4)
{
throw new ApiFailure((int)response.StatusCode, json?["error"]?["type"]?.GetValue<string>() ?? "unknown", requestId);
}
var delay = TimeSpan.FromSeconds(1 << (attempt - 1)) + TimeSpan.FromMilliseconds(Random.Shared.Next(250));
if (response.Headers.RetryAfter?.Delta is { } retryAfter && retryAfter > TimeSpan.Zero)
{
delay = retryAfter;
}
await Task.Delay(delay, cancellation);
}
}
public Task<JsonNode> VerifyEmailAsync(string email, CancellationToken cancellation) =>
CallAsync("email", new { email }, cancellation);
public Task<JsonNode> ValidatePhoneAsync(string phone, string? country, CancellationToken cancellation) =>
CallAsync("phone", string.IsNullOrEmpty(country) ? new { phone } : new { phone, country }, cancellation);
public Task<JsonNode> LookupIpAsync(string ip, CancellationToken cancellation) =>
CallAsync("ip", new { ip }, cancellation);
}
2. The endpoint
Put this in Program.cs:
using System.Net.Http.Headers;
using App.Validation;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient<ValidateClient>(client =>
{
client.BaseAddress = new Uri("https://api.qelka.com/v1/");
client.Timeout = TimeSpan.FromSeconds(15);
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", builder.Configuration["Validate:ApiKey"]);
});
var app = builder.Build();
app.MapPost("/signup", async (SignupRequest request, ValidateClient client, HttpContext context, ILogger<Program> logger) =>
{
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(context.RequestAborted);
deadline.CancelAfter(TimeSpan.FromSeconds(12));
var token = deadline.Token;
var errors = new Dictionary<string, string>();
var checkedAll = true;
var review = false;
string? e164 = null;
async Task<System.Text.Json.Nodes.JsonNode?> Settle(Func<Task<System.Text.Json.Nodes.JsonNode>> task)
{
try
{
return await task();
}
catch (ApiFailure failure) when (failure.Type == "unprocessable_input")
{
return null;
}
catch (Exception error) when (error is ApiFailure or HttpRequestException or OperationCanceledException)
{
checkedAll = false;
logger.LogWarning("validation skipped: {Type}", error is ApiFailure failure ? $"{failure.Type} request_id={failure.RequestId}" : error.GetType().Name);
return null;
}
}
var ip = context.Connection.RemoteIpAddress?.ToString();
var emailTask = string.IsNullOrEmpty(request.Email) ? Task.FromResult<System.Text.Json.Nodes.JsonNode?>(null) : Settle(() => client.VerifyEmailAsync(request.Email, token));
var phoneTask = string.IsNullOrEmpty(request.Phone) ? Task.FromResult<System.Text.Json.Nodes.JsonNode?>(null) : Settle(() => client.ValidatePhoneAsync(request.Phone, request.Country, token));
var ipTask = string.IsNullOrEmpty(ip) ? Task.FromResult<System.Text.Json.Nodes.JsonNode?>(null) : Settle(() => client.LookupIpAsync(ip, token));
await Task.WhenAll(emailTask, phoneTask, ipTask);
if (emailTask.Result is { } email)
{
var status = (string?)email["status"];
if (status == "undeliverable")
{
var suggestion = (string?)email["did_you_mean"];
errors["email"] = suggestion is null ? "This email address cannot receive mail." : $"Did you mean {suggestion}?";
}
else if (status == "risky" && (string?)email["reason"] == "disposable")
{
review = true;
}
}
if (phoneTask.Result is { } phone)
{
var status = (string?)phone["status"];
if (status == "invalid") errors["phone"] = "This phone number is not valid.";
else if (status == "valid") e164 = (string?)phone["e164"];
}
if (ipTask.Result is { } ipResult)
{
review |= (string?)ipResult["risk"]?["level"] == "high" || (bool?)ipResult["flags"]?["tor"] == true;
}
if (errors.Count > 0)
{
return Results.UnprocessableEntity(new { errors });
}
return Results.Created("/account", new { phone = e164 ?? request.Phone, needsReview = review, needsRecheck = !checkedAll });
});
app.Run();
record SignupRequest(string? Email, string? Phone, string? Country);
A failed call never adds an error: the signup goes through and needsRecheck is true, so a background job can check it again later. Only a clear negative answer blocks. 403 and 401 mean a wrong key, 402 an empty balance: all of them fail open here, so alert yourself.
In production behind a proxy, call app.UseForwardedHeaders with the proxies you trust before the endpoint, so RemoteIpAddress is the visitor. Add the built-in rate limiting middleware to the route so a bot cannot spend your credits through it. Store e164 instead of what was typed.
Read the result
| Result | Action |
|---|---|
Email undeliverable |
Reject with 422, show did_you_mean |
Email risky, reason disposable |
Flag, or reject if you block disposable inboxes |
Email unknown |
Accept and confirm by email |
Phone valid |
Store e164 |
Phone unknown |
No + and no country: send the country |
IP high risk or Tor |
Flag for review, add friction |
Handle errors and rate limits
No error is billed. 401 invalid_api_key and 403 forbidden mean a wrong or restricted key. 402 insufficient_credits means an empty balance: alert yourself and keep failing open. A key allows 200 requests per 10 seconds, then you get 429 rate_limited, and Retry-After says how long to wait. Each email check costs 1 credit. See Errors and Rate limits.
Related
Frequently asked questions
Why a typed client with AddHttpClient?
Where do I store the API key?
How do I get the client IP behind a proxy?
Put this check in your product
Get an API key in under a minute. 100 free credits every month, no card required.
- 100 free credits a month
- No card
- Test keys spend nothing
- Cancel any time