Skip to content

Integrations

Validate phone numbers and emails in C# and .NET

Check emails, phone numbers and IPs from C# with HttpClient and System.Text.Json. A typed client with timeouts, retries on rate limits and a fail-open signup check.

Updated 2026-11-23

This recipe calls the API from C# with HttpClient and System.Text.Json. It gives you typed results for email, phone and IP checks, a deadline on every call, retries that respect the rate limit and a signup decision that never blocks on an API problem.

What you need

  • .NET 8 or later. The code uses top-level types, records and nullable reference types.
  • A Qelka API key in the API_KEY environment variable. A sk_test_ key returns simulated results and never spends credits: see Test mode.
  • Server-side code only: see Authentication.

Steps

1. The client

csharp
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace App.Validation;

public sealed class ApiException(int status, string type, string message, string? requestId)
    : Exception($"{type}: {message}")
{
    public int Status { get; } = status;
    public string Type { get; } = type;
    public string? RequestId { get; } = requestId;
}

public sealed record EmailResult(
    [property: JsonPropertyName("status")] string Status,
    [property: JsonPropertyName("reason")] string Reason,
    [property: JsonPropertyName("did_you_mean")] string? DidYouMean);

public sealed record PhoneResult(
    [property: JsonPropertyName("status")] string Status,
    [property: JsonPropertyName("e164")] string? E164);

public sealed record IpFlags([property: JsonPropertyName("tor")] bool Tor);

public sealed record IpRisk([property: JsonPropertyName("level")] string Level);

public sealed record IpResult(
    [property: JsonPropertyName("flags")] IpFlags Flags,
    [property: JsonPropertyName("risk")] IpRisk Risk);

public sealed class ValidateClient(HttpClient http)
{
    private const string BaseUrl = "https://api.qelka.com/v1";
    private static readonly HashSet<HttpStatusCode> Retryable =
        [HttpStatusCode.TooManyRequests, HttpStatusCode.InternalServerError, HttpStatusCode.BadGateway, HttpStatusCode.ServiceUnavailable];

    public static ValidateClient FromEnvironment()
    {
        var http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
        http.DefaultRequestHeaders.Authorization =
            new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("API_KEY"));
        return new ValidateClient(http);
    }

    private async Task<T> CallAsync<T>(string path, object body, CancellationToken cancellation)
    {
        for (var attempt = 1; ; attempt++)
        {
            using var response = await http.PostAsJsonAsync(BaseUrl + path, body, cancellation);
            if (response.IsSuccessStatusCode)
            {
                return (await response.Content.ReadFromJsonAsync<T>(cancellation))!;
            }

            var requestId = response.Headers.TryGetValues("X-Request-Id", out var ids) ? ids.FirstOrDefault() : null;
            if (!Retryable.Contains(response.StatusCode) || attempt == 4)
            {
                using var document = await JsonDocument.ParseAsync(await response.Content.ReadAsStreamAsync(cancellation), cancellationToken: cancellation);
                var error = document.RootElement.GetProperty("error");
                throw new ApiException(
                    (int)response.StatusCode,
                    error.GetProperty("type").GetString() ?? "unknown",
                    error.GetProperty("message").GetString() ?? "",
                    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<EmailResult> VerifyEmailAsync(string email, CancellationToken cancellation = default) =>
        CallAsync<EmailResult>("/email", new { email }, cancellation);

    public Task<PhoneResult> ValidatePhoneAsync(string phone, string? country, CancellationToken cancellation = default) =>
        CallAsync<PhoneResult>("/phone", string.IsNullOrEmpty(country) ? new { phone } : new { phone, country }, cancellation);

    public Task<IpResult> LookupIpAsync(string ip, CancellationToken cancellation = default) =>
        CallAsync<IpResult>("/ip", new { ip }, cancellation);
}

The Retry-After header wins over the backoff on a 429. Every ApiException carries the documented error type and the X-Request-Id. See Errors and Rate limits.

2. Decide on a signup

csharp
namespace App.Validation;

public sealed record Verdict(bool Reject, IReadOnlyList<string> Reasons, bool Review, string? E164);

public sealed class SignupCheck(ValidateClient client)
{
    public async Task<Verdict> CheckAsync(string email, string phone, string? country, string? ip, CancellationToken cancellation = default)
    {
        using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
        deadline.CancelAfter(TimeSpan.FromSeconds(12));
        var token = deadline.Token;

        var reject = false;
        var review = false;
        string? e164 = null;
        var reasons = new List<string>();

        try
        {
            var result = await client.VerifyEmailAsync(email, token);
            if (result.Status == "undeliverable")
            {
                reject = true;
                reasons.Add(result.DidYouMean is null ? "This email address cannot receive mail." : $"Did you mean {result.DidYouMean}?");
            }
            else if (result.Status == "risky" && result.Reason == "disposable")
            {
                review = true;
            }
        }
        catch (Exception error) when (error is ApiException or HttpRequestException or OperationCanceledException)
        {
            Skipped(error);
        }

        try
        {
            var result = await client.ValidatePhoneAsync(phone, country, token);
            if (result.Status == "invalid")
            {
                reject = true;
                reasons.Add("This phone number is not valid.");
            }
            else if (result.Status == "valid")
            {
                e164 = result.E164;
            }
        }
        catch (Exception error) when (error is ApiException or HttpRequestException or OperationCanceledException)
        {
            Skipped(error);
        }

        if (!string.IsNullOrEmpty(ip))
        {
            try
            {
                var result = await client.LookupIpAsync(ip, token);
                review |= result.Risk.Level == "high" || result.Flags.Tor;
            }
            catch (ApiException error) when (error.Type == "unprocessable_input")
            {
            }
            catch (Exception error) when (error is ApiException or HttpRequestException or OperationCanceledException)
            {
                Skipped(error);
            }
        }

        return new Verdict(reject, reasons, review, e164);
    }

    private static void Skipped(Exception error) =>
        Console.Error.WriteLine(error is ApiException api
            ? $"validation skipped: {api.Type} status={api.Status} request_id={api.RequestId}"
            : $"validation skipped: {error.GetType().Name}");
}

A failed call never sets Reject: the signup goes through and you check it again later. Only a clear negative answer blocks.

3. Use it

In a minimal API, register the client once and inject it:

csharp
using App.Validation;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(_ => ValidateClient.FromEnvironment());
builder.Services.AddSingleton<SignupCheck>();
var app = builder.Build();

app.MapPost("/signup", async (SignupRequest request, SignupCheck check, HttpContext context) =>
{
    var verdict = await check.CheckAsync(request.Email, request.Phone, request.Country, context.Connection.RemoteIpAddress?.ToString());
    if (verdict.Reject)
    {
        return Results.UnprocessableEntity(new { errors = verdict.Reasons });
    }
    return Results.Created("/account", new { phone = verdict.E164 ?? request.Phone, needsReview = verdict.Review });
});

app.Run();

record SignupRequest(string Email, string Phone, string? Country);

Behind a proxy or load balancer, RemoteIpAddress is the proxy unless you configure the forwarded headers middleware and trust only the proxies you control. Store E164 instead of what was typed.

4. What the fields mean

Field Value Action
Email status undeliverable Reject, show did_you_mean
Email status risky Accept and flag, or reject disposable inboxes
Email status unknown Accept
Phone status valid Store e164
Phone status unknown Send country or ask for the + format
IP risk.level high Ask for extra verification

A 422 unprocessable_input on the IP is a private or loopback address, normal in local development, so the code ignores it. For many values at once, POST /batch takes up to 100 items in one request: see the batch reference.

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. Each email check costs 1 credit.

Frequently asked questions

Is there an official .NET package?
No. The official client is the JavaScript SDK, so in .NET you call the HTTP API directly. It is plain HTTPS and JSON with one Authorization header, and HttpClient with System.Text.Json covers it without any extra package. You can also generate a client from the public OpenAPI 3.1 document.
Should I create a new HttpClient for every call?
No. Keep one HttpClient for the life of the app, or register a typed client with AddHttpClient so the factory manages connections and DNS refresh. A new HttpClient per call can exhaust sockets under load. The client below takes an HttpClient in its constructor so either approach works.
How do I set a timeout?
Set HttpClient.Timeout for the longest call and pass a CancellationToken for anything shorter. Email checks in full mode wait for a mail server, so allow around ten seconds. On a timeout, accept the signup and check the address again later instead of blocking the person.

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