Guide

How to receive webhooks in C# (.NET) minimal receiver → production-ready processing

Start with a minimal “native” receiver, but don’t stop there. In production, reliable webhook handling means verification, retries, idempotency, and backpressure — which is where Hooque simplifies everything.

Building for a specific provider? Browse provider webhook APIs.

TL;DR

  • Treat “receive webhooks in C# (.NET)” as an ops problem, not just a route handler.
  • Verify the request before parsing/side effects (use a verifySignature(...) stub, then implement provider verification).
  • Return 2xx quickly; move work to a worker/queue to avoid timeouts and retries.
  • Assume retries and design idempotency (dedupe by event id + unique constraints).
  • Log + store raw payloads for replayable debugging.
  • If you need one workflow across many providers, centralize ingest + standardize consumption.

Deep dives: security, retries, queue migration.

Anti-patterns

  • Doing business logic inline in the C# (.NET) request handler.
  • Parsing/transforming the body before verification (breaks signing inputs).
  • Returning 2xx before authenticity is proven.
  • Skipping idempotency (retries become double side effects).

If you’re triaging a live incident, use the debugging playbook .

Framework shortcuts

If you’re already using a framework, jump straight to the minimal framework receiver, then reuse the same production guidance and Hooque consumer loops.

  1. ASP.NET Minimal APIs
    How to receive webhooks in ASP.NET Minimal APIs
  2. ASP.NET MVC
    How to receive webhooks in ASP.NET MVC
  3. Azure Functions
    How to receive webhooks in Azure Functions

Why it's hard in production

A route handler is the easy part. Supporting multiple senders means multiple security models, spikes, and retry semantics.

Verify authenticity + stop replays

Use a verifySignature(...) stub here, then implement real verification + replay defense for each provider.

Read the guide

Assume retries (duplicates are optional)

Treat every delivery as at-least-once and make side effects idempotent (DB constraints, dedupe keys).

Read the guide

Don’t do work in the request path

Ack fast, process async. Otherwise timeouts, deploys, and spikes turn into missed webhooks.

Read the guide

Debug with real payloads

Save the exact body + headers so you can replay deterministically after a fix.

Read the guide

Add monitoring + alerts early

Track delivered vs rejected, processing latency, queue depth, and error rates.

Read the guide

Iterate locally without losing events

Tunnels help, but durable capture + replay removes the “my laptop was asleep” problem.

Read the guide

Minimal “no framework” receiver (C# / .NET)

This is a minimal starting point. Keep verifySignature(...) as a stub here, then implement provider-specific verification and replay defense in the security guide .

// .NET Minimal APIs (.NET 6+)
// Run: dotnet run
using System;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

void VerifySignature(IHeaderDictionary headers, byte[] body)
{
  // don't compromise on security
  // TODO: implement provider-specific signature verification
}

void ProcessData(byte[] body)
{
  // TODO: your business logic (DB writes, external API calls, etc.)
}

app.MapPost("/webhooks", async (HttpContext ctx) =>
{
  using var ms = new MemoryStream();
  // gracefully handle body streams that abort unexpectedly
  try {
    await ctx.Request.Body.CopyToAsync(ms);
  } catch (Exception e) {
    Console.WriteLine($"failed to read body: {e.Message}");
    return Results.BadRequest();
  }
  
  var body = ms.ToArray();
  VerifySignature(ctx.Request.Headers, body);

  // What happens if it fails or times out?
  // Most providers retry -> duplicates unless you designed idempotency.
  ProcessData(body);

  // IMPORTANT: ack fast to avoid timeouts and duplicate deliveries.
  return Results.Text("ok", statusCode: 200);
});

Console.WriteLine("listening on http://localhost:3000/webhooks");
app.Run("http://localhost:3000");

Hooque turns any webhook into a reliable queue.

Non-obvious scenario: you can’t expose a port

In real deployments, the hardest part is often “where does this endpoint run?” (NAT, corporate networks, locked-down environments, short-lived preview deployments). Hooque decouples inbound receiving from processing so your C# (.NET) app doesn’t need to be the public receiver.

The easy path: receive with Hooque + consume forever

Hooque turns inbound webhooks into a durable queue. Your code becomes a run-forever worker that pulls or streams events and acks/nacks/rejects explicitly.

  • No need to run a public webhook endpoint in every environment (especially for local dev).
  • Durable capture + replay/inspection so “we missed the webhook” becomes debuggable.
  • Explicit Ack / Nack / Reject lifecycle so retries are under your control.
  • Backpressure and spike absorption: buffer now, process at your pace.
  • One consumption pattern across many senders (even if their security/retry rules differ).

Flow

  1. Provider delivers → Hooque ingest endpoint
  2. Hooque persists payload immediately
  3. Your worker pulls (REST) or streams (SSE)
  4. Your worker ack/nack/rejects explicitly

Hooque REST polling loop (runs forever)

Polling is a good default when you want a simple worker loop. It also works in environments where long-lived connections are unreliable.

// .NET 8+ (HttpClient)
// Runs forever: poll /next, ack/nack/reject explicitly.
using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Threading.Tasks;

var nextUrl = Environment.GetEnvironmentVariable("HOOQUE_QUEUE_NEXT_URL")
  ?? "https://app.hooque.io/queues/<consumerId>/next";
var token = Environment.GetEnvironmentVariable("HOOQUE_TOKEN") ?? "hq_tok_replace_me";

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

while (true)
{
  var msg = await GetNextMessageAsync();
  if (msg == null)
  {
    await Task.Delay(1000);
    continue;
  }

  try
  {
    await ProcessDataAsync(msg.Payload, msg.Meta);
    await AckAsync(msg);
  }
  catch (Exception e)
  {
    await NackAsync(msg, e);
  }
}

async Task<Msg?> GetNextMessageAsync()
{
  try
  {
    using var req = new HttpRequestMessage(HttpMethod.Get, nextUrl);
    req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

    using var resp = await client.SendAsync(req);
    if (resp.StatusCode == System.Net.HttpStatusCode.NoContent) return null;
    
    var body = await resp.Content.ReadAsStringAsync();
    if (!resp.IsSuccessStatusCode)
    {
      Console.WriteLine($"next() failed: {(int)resp.StatusCode} {body}");
      await Task.Delay(2000);
      return null;
    }

    var metaRaw = resp.Headers.TryGetValues("X-Hooque-Meta", out var vals) ? (vals.FirstOrDefault() ?? "{}") : "{}";
    var meta = JsonDocument.Parse(metaRaw).RootElement;

    return new Msg(body, meta);
  }
  catch (Exception e)
  {
    Console.WriteLine($"Worker connection err: {e.Message}");
    await Task.Delay(2000);
    return null;
  }
}

async Task ProcessDataAsync(string payload, JsonElement meta)
{
  Console.WriteLine($"event: {meta.GetProperty("messageId").GetString()}");
}

async Task AckAsync(Msg msg)
{
  if (msg.Meta.TryGetProperty("ackUrl", out var ackUrl))
  {
    await PostAsync(ackUrl.GetString()!, null);
  }
}

async Task NackAsync(Msg msg, Exception e)
{
  string? url = null;
  if (msg.Meta.TryGetProperty("nackUrl", out var nackUrl)) url = nackUrl.GetString();
  else if (msg.Meta.TryGetProperty("rejectUrl", out var rejectUrl)) url = rejectUrl.GetString();

  if (url != null)
  {
    await PostAsync(url, e.Message);
  }
}

async Task PostAsync(string url, string? reason)
{
  using var req = new HttpRequestMessage(HttpMethod.Post, url);
  req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
  if (reason != null)
  {
    req.Content = JsonContent.Create(new { reason });
  }
  await client.SendAsync(req);
}

record Msg(string Payload, JsonElement Meta);

Hooque SSE stream consumer (runs forever)

SSE is great for low-latency processing: keep a connection open, process events as they arrive, and reconnect on disconnects.

// .NET 8+ — SSE consumer (HttpClient)
// Runs forever: connect to /stream, handle "message" events, ack/nack/reject explicitly.
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

var streamUrl = Environment.GetEnvironmentVariable("HOOQUE_QUEUE_STREAM_URL")
  ?? "https://app.hooque.io/queues/<consumerId>/stream";
var token = Environment.GetEnvironmentVariable("HOOQUE_TOKEN") ?? "hq_tok_replace_me";
using var client = new HttpClient { Timeout = Timeout.InfiniteTimeSpan };

while (true)
{
  try
  {
    await foreach (var msg in GetMessageStreamAsync())
    {
      try
      {
        await ProcessDataAsync(msg.Payload, msg.Meta);
        await AckAsync(msg);
      }
      catch (Exception e)
      {
        await NackAsync(msg, e);
      }
    }
  }
  catch (Exception e)
  {
    Console.WriteLine("stream error: " + e.Message);
    await Task.Delay(2000);
  }
}

async IAsyncEnumerable<Msg> GetMessageStreamAsync([EnumeratorCancellation] CancellationToken cancellationToken = default)
{
  using var req = new HttpRequestMessage(HttpMethod.Get, streamUrl);
  req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
  req.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));

  using var resp = await client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
  resp.EnsureSuccessStatusCode();

  using var stream = await resp.Content.ReadAsStreamAsync(cancellationToken);
  using var reader = new StreamReader(stream);
  string? evt = null;
  var data = new StringBuilder();

  while (!reader.EndOfStream)
  {
    var line = await reader.ReadLineAsync(cancellationToken);
    if (line == null) break;
    if (line.StartsWith(":")) continue;
    if (line.Length == 0)
    {
      if (evt == "message" && data.Length > 0)
      {
        using var doc = JsonDocument.Parse(data.ToString());
        var meta = doc.RootElement.GetProperty("meta").Clone();
        yield return new Msg(data.ToString(), meta);
      }
      evt = null;
      data.Clear();
      continue;
    }
    if (line.StartsWith("event:")) evt = line.Substring(6).Trim();
    if (line.StartsWith("data:"))
    {
      if (data.Length > 0) data.Append('\n');
      data.Append(line.Substring(5).TrimStart());
    }
  }
}

async Task ProcessDataAsync(string payload, JsonElement meta)
{
  Console.WriteLine($"event: {meta.GetProperty("messageId").GetString()}");
}

async Task AckAsync(Msg msg)
{
  if (msg.Meta.TryGetProperty("ackUrl", out var ackUrl))
  {
    await PostAsync(ackUrl.GetString()!, null);
  }
}

async Task NackAsync(Msg msg, Exception e)
{
  string? url = null;
  if (msg.Meta.TryGetProperty("nackUrl", out var nackUrl)) url = nackUrl.GetString();
  else if (msg.Meta.TryGetProperty("rejectUrl", out var rejectUrl)) url = rejectUrl.GetString();

  if (url != null)
  {
    await PostAsync(url, e.Message);
  }
}

async Task PostAsync(string url, string? reason)
{
  using var req = new HttpRequestMessage(HttpMethod.Post, url);
  req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
  if (reason != null)
  {
    req.Content = JsonContent.Create(new { reason });
  }
  await client.SendAsync(req);
}

record Msg(string Payload, JsonElement Meta);

FAQ

Quick answers for the questions that come up right before you ship.

What status code should I return for webhooks in C# (.NET)?

General: Usually return a fast 2xx after validating authenticity and basic schema. Timeouts and 5xx commonly trigger retries.

How Hooque helps: Hooque acknowledges ingest immediately and persists the payload. Your worker acks/nacks/rejects explicitly after processing.

Do I need signature verification in C# (.NET)?

General: Yes, unless the sender is fully trusted and on a private network. A public endpoint without verification is easy to forge and easy to replay.

How Hooque helps: Hooque can verify at ingest for supported providers or using generic strategies. Either way, your worker receives a normalized meta object and can stay focused on processing.

Why do I see duplicate webhook events in C# (.NET)?

General: Retries are normal: timeouts, transient network failures, and 5xx responses all produce duplicates. Design idempotency around event ids and side-effect boundaries.

How Hooque helps: Hooque makes delivery outcomes explicit (ack/nack/reject) and provides replay/inspection so you can fix issues without guessing what was received.

How do I test webhooks locally in C# (.NET)?

General: You can use a tunnel, but local dev still breaks on sleep, VPNs, clock skew, and signature-byte mismatches.

How Hooque helps: With Hooque you can avoid inbound locally: receive events into a durable queue and pull/stream to your laptop, then replay from the UI after changes.

Should I use REST polling or SSE streaming for webhook processing?

General: Use REST polling for simple batch workers and environments without long-lived connections. Use SSE for low-latency “process as it arrives” flows.

How Hooque helps: Hooque supports both: `GET /next` for polling and `GET /stream` for streaming. Both include meta with ready-to-call ack/nack/reject URLs.

Start processing webhooks reliably

Create a webhook endpoint, receive events, then run your worker forever using REST polling or SSE streaming — with explicit ack/nack/reject control.

No credit card required