Typical Webhook Signature Verification Error (.NET / ASP.NET Core)
When middleware consumes the raw HTTP stream, JSON gets re-serialized before hashing, or encoding/prefixes mismatch in .NET / ASP.NET Core, your server logs an exception matching the output below:
System.NotSupportedException: Specified method is not supported (Request.Body.Position = 0) — Request.EnableBuffering() was not called before reading raw webhook stream.
Raw Request Stream Handling & Replay Protection in .NET / ASP.NET Core
Verifying webhook HMAC-SHA256 signatures in ASP.NET Core 8 and 9 Web APIs (whether Minimal APIs or MVC Controllers) revolves around one fundamental Kestrel stream rule: HttpRequest.Body is a forward-only, non-seekable network stream by default. If ASP.NET Core model binding ([FromBody] MyEventDto payload) reads the stream first, you cannot rewind it; and serializing the C# DTO back via JsonSerializer.Serialize(payload) destroys the original JSON formatting and invalidates the HMAC.
To inspect untouched raw bytes cleanly in .NET 8 and 9, call request.EnableBuffering() BEFORE reading the stream (either inside a dedicated endpoint filter / middleware or directly at the top of a Minimal API handler without a [FromBody] parameter). Reading the stream with StreamReader(.., leaveOpen: true) and resetting request.Body.Position = 0 lets downstream JSON deserialization or logging read the exact same payload safely.
For cryptographic verification, .NET provides HMACSHA256 and CryptographicOperations.FixedTimeEquals(ReadOnlySpan<byte>, ReadOnlySpan<byte>) directly in System.Security.Cryptography; zero external NuGet dependencies required. Unlike string == comparison, FixedTimeEquals executes in constant time and safely returns false (without throwing an exception!) if the two byte spans differ in length.
When deploying ASP.NET Core behind Nginx, remember to match Nginx client_max_body_size with Kestrel's MaxRequestBodySize and offload slow downstream database or HTTP calls to a Channel<T> + BackgroundService (or Hangfire/MassTransit) so webhook senders receive HTTP 200 OK in milliseconds.
Use the interactive Web Crypto debugger above to generate Hex or Base64 test signatures across Stripe, GitHub, Shopify, Slack, or Generic HMAC formats and copy the complete C# snippet.
Enterprise ASP.NET Core 8 and 9 webhook receivers benefit from encapsulating EnableBuffering(), UTF-8 raw stream reading, and CryptographicOperations.FixedTimeEquals() inside a reusable IEndpointFilter or middleware scoped strictly to /webhooks/* routes. Combined with .NET's System.Threading.Channels or MassTransit for asynchronous fulfillment and structured Serilog telemetry on verification failures, your Kestrel API handles high-volume webhook bursts reliably behind Nginx.
Step-by-Step .NET / ASP.NET Core Webhook Verification Setup
Follow each step below to preserve untouched raw request bytes, enforce constant-time HMAC verification, and offload webhook jobs asynchronously for fast 2xx acknowledgments.
1Build a Reusable ASP.NET Core Endpoint Filter for Raw Body HMAC Checks
Filters/WebhookHmacEndpointFilter.csCall EnableBuffering(), compute HMACSHA256 over the untouched UTF-8 bytes, verify in constant time via CryptographicOperations.FixedTimeEquals(), and rewind Body.Position to 0.
Filters/WebhookHmacEndpointFilter.cscsharpusing System.Security.Cryptography; using System.Text; public sealed class WebhookHmacEndpointFilter(IConfiguration config) : IEndpointFilter { public async ValueTask<object?> InvokeAsync( EndpointFilterInvocationContext context, EndpointFilterDelegate next) { var request = context.HttpContext.Request; request.EnableBuffering(); request.Body.Position = 0; using var reader = new StreamReader(request.Body, Encoding.UTF8, leaveOpen: true); var rawBody = await reader.ReadToEndAsync(); request.Body.Position = 0; var received = request.Headers["X-Signature-256"].ToString(); var secret = config["Webhooks:Secret"] ?? string.Empty; if (string.IsNullOrEmpty(received) || string.IsNullOrEmpty(secret)) return Results.Unauthorized(); using var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret)); var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(rawBody)); var expected = Convert.ToHexString(hash).ToLowerInvariant(); var valid = CryptographicOperations.FixedTimeEquals( Encoding.UTF8.GetBytes(expected), Encoding.UTF8.GetBytes(received) ); return valid ? await next(context) : Results.Unauthorized(); } }2Attach the Filter to Your Minimal API Webhook Endpoint
Program.csBecause the filter rewinds request.Body.Position = 0 after verifying the raw stream, your endpoint handler can still bind a strongly typed C# record cleanly.
Program.cscsharpapp.MapPost("/webhooks/orders", (OrderWebhookEvent payload) => { // Signature is already verified over raw bytes! return Results.Accepted(value: new { payload.EventId }); }) .AddEndpointFilter<WebhookHmacEndpointFilter>();3Configure Webhooks__Secret via Environment Variables in Linux/Docker
.envInject Webhooks:Secret using ASP.NET Core's double-underscore convention so secrets never live in appsettings.json.
.envdotenvWebhooks__Secret="whsec_demo_dotnet_kestrel_secret_2026"4Test With curl Using --data-binary and Generated Signature
terminalSend a formatted JSON file with --data-binary so curl preserves exact newlines and indentation.
terminalbashcurl -i -X POST http://127.0.0.1:5000/webhooks/orders \ -H "Content-Type: application/json" \ -H "X-Signature-256: <paste_hex_from_tool>" \ --data-binary @order-event.json
Common .NET / ASP.NET Core Webhook Pitfalls
Avoid these three subtle production failure modes when verifying external webhook signatures.
Forgetting leaveOpen: true on StreamReader Closing Request.Body Prematurely
Disposing a default StreamReader closes the underlying Request.Body stream, causing subsequent JSON model binding to throw ObjectDisposedException. Always pass leaveOpen: true and rewind Position = 0.
Convert.ToHexString() Returning Uppercase Hex in .NET
In .NET 5–8, Convert.ToHexString() returns UPPERCASE hex ("A1B2.."), whereas Stripe, GitHub, and Slack send lowercase hex ("a1b2.."). Always call .ToLowerInvariant() (or Convert.ToHexStringLower() in .NET 9+).
Enabling EnableBuffering() Globally for Massive File Upload Endpoints
Buffering large requests in memory/disk can increase memory pressure under attack. Apply EnableBuffering() selectively only on /webhooks/* endpoints using an Endpoint Filter or scoped middleware.
Audit Your Webhook Signing Secrets & Nginx Reverse Proxy Headers
Make sure your .env signing secret has no trailing spaces or unquoted # truncation and your Nginx proxy forwards raw POST payloads without 301 redirects:
Validate ASP.NET Core 8/9 Linux and Docker .env files locally. Map double-underscore __ hierarchy keys to appsettings.json, ConnectionStrings, and CORS arrays.
Build a production Nginx reverse proxy for ASP.NET Core 8/9 Kestrel on port 5000 with UseForwardedHeaders, SignalR WebSockets, SSL, and large OAuth headers.
Frequently Asked Questions
- Does CryptographicOperations.FixedTimeEquals throw an exception if lengths differ?
- No. Unlike Node.js crypto.timingSafeEqual (which throws RangeError on mismatched lengths), .NET's CryptographicOperations.FixedTimeEquals safely returns false when the two ReadOnlySpan<byte> lengths differ.
- How do I adapt this ASP.NET Core filter for Shopify Base64 HMAC headers?
- Replace Convert.ToHexString(hash).ToLowerInvariant() with Convert.ToBase64String(hash) and read the X-Shopify-Hmac-Sha256 header instead.
- Why does [FromBody] return an empty body if I read Request.Body inside an MVC Controller?
- MVC model binding runs BEFORE your controller action executes, consuming the non-seekable stream first. Either enable buffering in a Middleware/ResourceFilter before model binding, or omit [FromBody] and deserialize rawBody manually with JsonSerializer.Deserialize<T>(rawBody).
- Should I run AllowAnonymous on ASP.NET Core webhook endpoints?
- Yes, if your API uses a global JWT fallback authorization policy. Mark webhook routes [AllowAnonymous] and rely on your HMAC signature filter to authenticate external webhook providers.
Related Webhook HMAC Verification Guides
Browse all 10 webhook guides →Stripe Webhook Signature Verification in Laravel (Raw Body & CSRF Fix)
Fix Stripe SignatureVerificationException in Laravel 11/12 using $request->getContent(), CSRF exclusion in bootstrap/app.php, hash_equals, and async queues.
Stripe Webhook Signature Verification in FastAPI (request.body() Guide)
Fix Stripe webhook signature errors in Python FastAPI. Read raw bytes with await request.body() before Pydantic parsing and compare via hmac.compare_digest.
GitHub Webhook X-Hub-Signature-256 Verification in Node.js Express
Verify GitHub X-Hub-Signature-256 HMAC-SHA256 webhooks in Express.js using raw Buffers, sha256= prefix validation, and crypto.timingSafeEqual.
Shopify Base64 HMAC Webhook Verification in Python FastAPI
Fix Shopify X-Shopify-Hmac-Sha256 webhooks in Python FastAPI. Use base64.b64encode on raw digest bytes, await request.body(), and hmac.compare_digest.