Webhooks in ASP.NET Core: A Complete Guide with Example

Modern applications often need to communicate with external services in real time. For example, a payment service may need to notify your application when a payment is completed, or a Git hosting platform may need to notify your application when a new commit is pushed. One common way to receive these real-time notifications is through Webhooks.

A Webhook is an HTTP callback mechanism that allows one application or service to automatically send data to another application when a specific event occurs. Instead of continuously sending requests to check whether something has changed, your application provides a URL, and the external service sends an HTTP request to that URL whenever the configured event occurs.

ASP.NET Core makes it straightforward to create webhook endpoints using controllers or Minimal APIs. In this article, we will understand what webhooks are, how they work, and how to implement a webhook endpoint in an ASP.NET Core application with a practical example. We will also look at important considerations such as request validation, security, error handling, retries, and idempotency when building production-ready webhooks.

What is a Webhook?

A Webhook is a mechanism that allows one application to automatically send information to another application when a specific event occurs.

In simple terms, a webhook is a notification sent from one application to another over HTTP. The receiving application provides a URL, known as a webhook endpoint, and the external service sends an HTTP request to that URL whenever an event occurs.

For example, suppose you have an ASP.NET Core e-commerce application that needs to know when a customer completes a payment. Instead of continuously asking the payment provider service whether the payment has been completed, you can provide a webhook URL such as:

</> http
https://example.com/api/webhooks/payment

When the payment is completed, the payment provider service sends an HTTP POST request to this URL containing information about the payment.

How Does a Webhook Work

The basic webhook flow looks like this:
How Webhooks Work
The process can be summarized in three steps:
  1. An event occurs – For example, a customer successfully completes a payment.
  2. The external service sends a request – The service sends an HTTP POST request to your webhook endpoint with the event information.
  3. Your application processes the event – The ASP.NET Core application receives the request, validates the data, and performs the required operation, such as updating a database.

Webhook Example Consider an online payment application.

A customer makes a payment of ₹1,500. Once the payment is successfully completed, the payment provider can send a webhook request to your ASP.NET Core application.

The request might contain the following JSON:
</> JSON
{ 
	"event": "payment.completed", 
    "paymentId": "PAY-1001", 
    "amount": 1500, 
    "currency": "INR", 
    "status": "completed" 
}

Your ASP.NET Core application receives this request through a webhook endpoint:
</> http
POST /api/webhooks/payment

The application can then use the information to update the payment status in the database, update the customer's order, send a confirmation email, or perform other business operations.

Webhook vs API

Webhooks and APIs are both used for communication between applications, but they work in different ways.

The main difference is who initiates the communication.

With an API, your application typically sends a request to another service to retrieve or modify information. With a webhook, an external service sends a notification to your application when a specific event occurs.

Key Differences
FeatureAPIWebhook
CommunicationRequest and responseEvent notification
Who initiates the request?Usually your applicationExternal service
Communication stylePullPush
When is data sent?When your application requests itWhen an event occurs
Typical HTTP methodGET, POST, PUT, DELETE, etc.Usually POST
Requires polling?SometimesUsually not
Common use casesRetrieve or modify dataReceive event notifications
ExampleGet payment statusPayment completed notification

Why Use Webhooks in ASP.NET Core?

Webhooks are useful in ASP.NET Core applications when your application needs to know about events that occur in an external system. Instead of repeatedly calling an API to check whether something has changed, your application can expose a webhook endpoint and receive a notification when the event occurs.

  1. Receive Real-Time Notifications

    Webhooks allow your application to receive notifications as soon as an event occurs. For example, when a customer completes a payment, a payment provider can immediately send a webhook to your ASP.NET Core application.

  2. Avoid Continuous Polling

    Without webhooks, your application might repeatedly call an external API to check whether an event has occurred. This approach is known as polling and can result in unnecessary network requests.

    With a webhook, the external service sends the notification when the event actually occurs.

  3. Reduce Unnecessary API Requests

    Polling can generate many requests even when there is no new information.For example, an application might check a payment status every 30 seconds. Most of these requests may not provide any new information.

    With a webhook, the payment provider can notify the application when the payment is completed.

  4. Enable Event-Driven Communication

    Webhooks provide a simple way for an ASP.NET Core application to respond to events generated by external systems.

    For example, an external service might generate events such as payment completed or order created. Your application can process each event according to its business requirements.

    This approach allows your application to react to events instead of continuously checking for changes.

  5. Automate Business Processes

    A webhook can trigger one or more automated operations in your application. For example, when an order is created, webhook can Update Database, Send Email and Notify Administrator.

Creating a Webhook Endpoint in ASP.NET Core

Webhooks are a simple way for one application to notify another application when an event occurs. Instead of continuously asking an external service whether something has changed, your ASP.NET Core application can expose an HTTP endpoint that receives notifications automatically.

In this guide, we will create a complete webhook endpoint in ASP.NET Core and learn how to:

  • Create a webhook API endpoint
  • Define a webhook request model
  • Receive JSON payloads
  • Process webhook events
  • Validate incoming requests
  • Secure a webhook endpoint
  • Log webhook requests
  • Handle errors
  • Test the webhook using Postman
  • Implement a more production-ready webhook design

Create an ASP.NET Core Web API Project

First step is we will create the template of dotnet core Web API project. The following steps helps to create Web API.
  1. Open Microsoft Visual Studio.
  2. Click on Create a new Project.
  3. Enter Web API in the search box
  4. Select the ASP.NET Core Web API template and select Next.
  5. In the Configure your new project dialog, name the project StudentManager and select Next.
  6. In the Additional information dialog:
    • Confirm the Framework is .NET 6.0 (Long-term support).
    • Confirm the checkbox for Use controllers (uncheck to use minimal APIs) is checked.
    • Select Create.

Create a Webhook Request Model

The external service will normally send webhook information as JSON.

For example:
</> JSON
{
  "eventId": "12345",
  "eventType": "payment.completed",
  "createdAt": "2026-10-04T10:30:00Z",
  "data": {
    "paymentId": "PAY-1001",
    "amount": 2500,
    "currency": "INR"
  }
}

Create a model called WebhookRequest.cs:
</> C#
public class WebhookRequest
{
    public string EventId { get; set; }

    public string EventType { get; set; }

    public DateTime CreatedAt { get; set; }

    public PaymentData Data { get; set; }
}

Create the PaymentData.cs model:
</> C#
public class PaymentData
{
    public string PaymentId { get; set; }

    public decimal Amount { get; set; }

    public string Currency { get; set; }
}

These classes represent the JSON payload sent by the webhook provider.

Create the Webhook Controller

Now create a controller called by adding the following code:
</> C#
using Microsoft.AspNetCore.Mvc;

namespace WebhookDemo.Controllers
{
    [ApiController]
    [Route("api/webhooks")]
    public class WebhooksController : ControllerBase
    {
        [HttpPost("payment")]
        public IActionResult PaymentWebhook(
            [FromBody] WebhookRequest request)
        {
            if (request == null)
            {
                return BadRequest();
            }

            Console.WriteLine(
                $"Event: {request.EventType}");

            Console.WriteLine(
                $"Payment ID: {request.Data.PaymentId}");

            Console.WriteLine(
                $"Amount: {request.Data.Amount}");

            return Ok();
        }
    }
}

Your webhook endpoint is now:
</> http
    POST /api/webhooks/payment
    

For example:
</> http
    https://localhost:7000/api/webhooks/payment
    

Test the Webhook Using Postman

You can test your webhook using Postman.
  1. Create a new POST request: https://localhost:7000/api/webhooks/payment
  2. Select: Body → raw → JSON
  3. Then provide:
    </> JSON
    {
        "eventId": "12345",
        "eventType": "payment.completed",
        "createdAt": "2026-10-04T10:30:00Z",
        "data": {
            "paymentId": "PAY-1001",
            "amount": 2500,
            "currency": "INR"
        }
    }
    

  4. Make sure the request contains: Content-Type: application/json
  5. Click Send.
  6. If everything is configured correctly, your API should return: 200 OK

Securing Webhook Endpoint

Security is one of the most important parts of webhook implementation.

Without authentication or verification, anyone who knows your endpoint URL could potentially send fake webhook requests.

A common approach is to use a webhook secret.

For example, the sender can send a signature in a header:
</> http
X-Webhook-Signature: abc123...


Your application calculates its own signature and compares the two values.

A common technique is HMAC-SHA256.

Handle Webhook Exceptions

Webhook failures are common in real-world applications. A webhook provider may send a request when an event occurs, but your application could be temporarily unavailable, the request may contain invalid data, or processing the event may fail.

A good webhook implementation should therefore be designed to detect failures, return appropriate HTTP status codes, log errors, and safely handle retries.

For example:
</> C#
[HttpPost("payment")]
public async Task<IActionResult> PaymentWebhook(
[FromBody] WebhookRequest request)
{
  try
  {
    if (request == null)
    {
      return BadRequest();
    }
    await ProcessWebhook(request);
    return Ok();
  }
  catch (Exception ex)
  {
    _logger.LogError(
    ex,
    "Error processing webhook {EventId}",
    request?.EventId);
    return StatusCode(500);
  }
}

The webhook provider can then retry the request if your application returns a server error, depending on the provider's retry behavior.

Return Appropriate HTTP Status Codes

Status CodeMeaning
200 OKWebhook was successfully processed
202 AcceptedWebhook was accepted for processing
400 Bad RequestPayload is invalid
401 UnauthorizedAuthentication/signature failed
403 ForbiddenRequest is not allowed
500 Internal Server ErrorTemporary/server-side processing failure

Best Practices for Webhooks

A webhook endpoint may look like a simple HTTP POST endpoint, but production webhook integrations require careful consideration of security, reliability, performance, and error handling.

The following best practices can help you build reliable and secure webhooks in ASP.NET Core.
  1. Always Use HTTPS

    Webhook endpoints should use HTTPS to protect data while it is being transmitted. HTTPS helps protect the webhook payload from being intercepted or modified during transmission.

  2. Verify Webhook Signatures

    Do not assume that every request received by your webhook endpoint came from the expected service.

    A malicious user could discover your webhook URL and send a fake request.

    Many webhook providers include a signature in the request headers. Your application should verify this signature before processing the request.

  3. Keep Webhook Secrets Secure

    Webhook secrets should never be hard-coded in your source code, store secrets in configuration or a secure secret-management system. For production applications, use an appropriate secret-management solution rather than committing secrets to source control.

  4. Make Webhook Processing Idempotent

    One of the most important webhook practices is idempotency. A webhook provider may send the same event multiple times because of retries or network problems. Use a unique event ID to identify each webhook event, this prevents duplicate processing.

  5. Return a Response Quickly Webhook providers generally expect your endpoint to respond within a reasonable amount of time. Avoid performing lengthy operations directly inside the webhook request. This reduces the possibility of timeouts and allows the webhook provider to know quickly that the event was received.
  6. Handle Retries Correctly

    Webhook providers commonly retry requests when delivery fails. Your application should therefore be prepared to receive the same event more than once. Do not assume that one webhook event will always result in exactly one HTTP request.

  7. Return Appropriate HTTP Status Codes: Use HTTP status codes to communicate the result of webhook processing.
  8. Validate the Incoming Payload

    Never blindly trust data received from an external system. Use model validation to make sure required fields are present and contain valid values. You should also validate values according to your application's business rules.

  9. Validate the Event Type

    Your webhook endpoint may receive multiple types of events. Don't process unknown event types as if they were valid. This prevents unexpected data from entering your business logic.

  10. Log Webhook Events: Logging is extremely useful when troubleshooting webhook delivery and processing problems.

Summary

Webhooks provide an efficient way for applications to receive real-time notifications when events occur. In this article, we explored how webhooks work, how they differ from APIs, and how to create and test a webhook endpoint in ASP.NET Core.

We also covered important aspects such as security, failure handling, and best practices. By following these practices, you can build secure, reliable, and maintainable webhook integrations in ASP.NET Core.

Thanks

Kailash Chandra Behera

I am an IT professional with over 12 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies.

Previous Post Next Post

نموذج الاتصال