← Back to list

Azure Service Bus Queue with .NET Web API and Azure Functions

raw-hitt · 2026-07-05 21:01 · 1 claps · 6.5 min read
#azure-service-bus #service-bus-queue #webapi #azure-functions #message-queue
Open on Medium ↗
Wiki topics: ☁️ · DevOps & Cloud

Event-Driven Processing Using Azure Functions and Service Bus in .NET

Modern applications demand scalability, reliability, and responsiveness. In this article, we explore how to build an asynchronous order processing system using a .NET Web API integrated with Azure Service Bus Queue. When an order is placed via the API, it is pushed to a queue, which then triggers an Azure Functions to process the message and send an email notification. This decoupled architecture ensures smooth handling of requests without blocking the main application flow.

Please note while performing this you might encounter various errors, I have given remedy to all the errors I had faced at the end of the implementation.

⚙️ When and Why to Use This

This pattern is useful when you want to separate your application components and handle tasks asynchronously. Using Azure Service Bus helps in managing high traffic, retry mechanisms, and message durability. It ensures that even if downstream services (like email notifications) are temporarily unavailable, the messages are not lost. Combined with Azure Functions, it provides a scalable, serverless way to process background jobs efficiently.

🧩 Use Case

Imagine an e-commerce platform where users place orders through a .NET Web API. Instead of processing everything instantly, the order details are pushed to a Azure Service Bus Queue. An Azure Functions listens to this queue and processes each order asynchronously. Once processed, it sends an email notification confirming the order placement. This approach improves system performance, avoids API delays, and ensures reliable communication even during peak loads.

🚀 Architecture

.NET Web API → Service Bus Queue → Azure Function → Email Notification

🧱 STEP 1: Create Service Bus (Azure Portal)

1. Create Namespace

  • Go to Azure Portal → Service Bus
  • Click Create
  • Pricing: Basic
  • Name: order-sb-demo

Create Queue a in Service bus

  • Go to Resource
  • Click + Queue

Create .NET Web API Projecct

In your Visual Studio, create a Web API project.

In the project install the NuGet package Azure.Messaging.ServiceBus.

Model —

We will be using the below model class

 public class Order
 {
     public int Id { get; set; }
     public string Product { get; set; }
     public string Email { get; set; }
 }

The Service

using Azure.Messaging.ServiceBus;
using System.Text.Json;

public class ServiceBusService
{
    private readonly string _connectionString;
    private readonly string _queueName = "order-queue";

    public ServiceBusService(IConfiguration config)
    {
        _connectionString = config["ServiceBusConnection"];
    }

    public async Task SendMessageAsync(Order order)
    {
        await using var client = new ServiceBusClient(_connectionString);
        var sender = client.CreateSender(_queueName);

        string messageBody = JsonSerializer.Serialize(order);
        var message = new ServiceBusMessage(messageBody);

        await sender.SendMessageAsync(message);
    }
}

This service sends order data to an Azure Service Bus Queue using the Azure.Messaging.ServiceBus.

It reads the connection string from configuration and creates a ServiceBusClient to connect to Azure.

Inside SendMessageAsync, the Order object is serialized into JSON format and wrapped into a ServiceBusMessage.

A sender is then created for the “order-queue” and the message is sent asynchronously. This enables decoupled communication between the API and downstream processing systems like Azure Functions.

Order controller

[ApiController]
[Route("api/[controller]")]
public class OrderController : ControllerBase
{
    private readonly ServiceBusService _service;

    public OrderController(ServiceBusService service)
    {
        _service = service;
    }

    [HttpPost]
    public async Task<IActionResult> PlaceOrder(Order order)
    {
        await _service.SendMessageAsync(order);
        return Ok("Order placed successfully!");
    }
}

The PlaceOrder API endpoint accepts an order request and sends it to Azure Service Bus Queue using a service method. It then immediately returns a success response without waiting for further processing, enabling asynchronous handling via services like Azure Functions.

🔧 appsettings.json

{
  "ServiceBusConnection": "<your-connection-string>"
}

Make sure you configure connection string in appsettings.json.

To get the Connection String

  • Go to settings → Shared Access Policies
  • Click: RootManageSharedAccessKey
  • Copy Connection String

👉If you are enjoying this Article, leave a clap and 👉 Follow me on Medium for more informational articles like this. 👨‍💻Connect with me on LinkedIn

👉If you are enjoying this Article, leave a clap and 👉 Follow me on Medium for more informational articles like this. 👨‍💻Connect with me on LinkedIn

⚙️Creating Azure Function (Consumer)

  1. In your Visual Studio, create a new project.
  2. In the templates select Azure functions.
  3. Runtime: .NET.
  4. Template: Service Bus Queue Trigger

Trigger Function Code

using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
using System.Net;
using System.Net.Mail;
using System.Text.Json;

public class Order
{
    public int Id { get; set; }
    public string Product { get; set; }
    public string Email { get; set; }
}

public static class OrderProcessor
{
    [FunctionName("OrderProcessor")]
    public static void Run(
        [ServiceBusTrigger("order-queue", Connection = "ServiceBusConnection")] string message,
        ILogger log)
    {
        var order = JsonSerializer.Deserialize<Order>(message);

        log.LogInformation($"Processing Order: {order.Id}");

        SendEmail(order);
    }

    private static void SendEmail(Order order)
    {
        var smtp = new SmtpClient("smtp.gmail.com")
        {
            Port = 587,
            Credentials = new NetworkCredential("your-email@gmail.com", "your-app-password"),
            EnableSsl = true
        };

        smtp.Send("your-email@gmail.com",
                  order.Email,
                  "Order Confirmation",
                  $"Your order for {order.Product} is placed successfully!");
    }
}
  1. In this code, I’ve created an Azure Functions named OrderProcessor that gets triggered whenever a new message arrives in the Azure Service Bus Queue called “order-queue”.
  2. The incoming message is in JSON format, so I deserialize it into an Order object to extract details like Id, Product, and Email.
  3. I then log the order processing information for monitoring purposes. After that, I call a helper method SendEmail to notify the customer. Inside this method, I configure an SMTP client (Gmail in this case) and send an order confirmation email.
  4. This way, I’ve implemented an asynchronous flow where order placement and email notification are completely decoupled.
  5. Make sure you have configured the connection string of Service Bus in local.settings.json:
{
  "Values": {
    "ServiceBusConnection": "<connection-string>"
  }
}

Creating a function app

  1. Go to Azure Portal
  2. Click on Create a resource → Search Function App.
  3. Select Consumption (Windows) Click Create.
  4. In the basics tab,
  5. Select subscription
  6. Select resource group
  7. Give the function app name → order-function-app
  8. Make sure you select the region same as Service Bus.
  9. Select the runtime stack .NET ✅.
  10. Version.NET 8
  11. OS → Windows
  12. Click on Review + Create
  13. Once the runction is creaed, go to the function and in left panel click: Environment variables.
  14. You’ll see: App settings tab, enter the connection string of your service bus and make sure the name is same as the connection string you gave when creating your azure function app in Visual Studio.
  15. Click Apply & again click apply to make sure your connection string is saved on the environment variables.

If you are enjoying this Article, leave a clap and 👉 Follow me on Medium for more informational articles like this. 👨‍💻Connect with me on LinkedIn

If you are enjoying this Article, leave a clap and 👉 Follow me on Medium for more informational articles like this. 👨‍💻Connect with me on LinkedIn

Publish function app from visual studio

  1. Right Click and publish your azure Function.
  2. In Target select Azure & click next.
  3. In Target select function App, select your newly created Azure function.
  4. Click create and hit publish.

🧪 Testing

Step 1: Run your API → send order

Step 2: Go to your service bus Queue you can see one message in queue.

Step 3: Go to:👉 Function App → Log Stream

You can see the logs we have logged in the function app and also check out the email on execution we are sending a mail to the email Id we are passing in the API.

Git Repo for Function App —

[embed]GitHub - raw-hitt/FunctionApp-Service-Bus: Function app using service bus Function app using service bus. Contribute to raw-hitt/FunctionApp-Service-Bus development by creating an account on…github.com

Git Repo for API —

[embed]GitHub - raw-hitt/ServiceBus-OrderSender Contribute to raw-hitt/ServiceBus-OrderSender development by creating an account on GitHub.github.com

✅ Conclusion

Using Azure Service Bus Queue with .NET Web API and Azure Functions enables a robust, scalable, and loosely coupled architecture. It enhances fault tolerance and ensures seamless background processing. This design pattern is ideal for modern cloud-native applications where reliability and performance are critical.

Troubleshooting

Error — The listener for function ‘OrderProcessor’ was unable to start.

🔥 Most Likely Root Cause

👉 One of these:

  1. ServiceBusConnection not set properly
  2. ❌ Wrong connection string
  3. ❌ Queue name mismatch

Make sure connection string exists in environment variables

Related Articles —

[embed]Docker & Containers: Powering the Next Wave of Modern Software Development medium.com

[embed]Azure Durable Functions Deep Dive: The Role of Orchestrator Functions In the world of serverless computing, managing long-running, stateful workflows can be challenging. That’s where Azure…medium.com

[embed]Analytical Workload in Azure An Analytical Workload in Azure is designed to handle large volumes of data and provide meaningful insights for…medium.com


메타데이터
post_id
f026a2de6b7a
slug
azure-service-bus-queue-with-net-web-api-and-azure-functions-f026a2de6b7a
url
https://medium.com/@rp99452/azure-service-bus-queue-with-net-web-api-and-azure-functions-f026a2de6b7a
canonical_url
https://medium.com/@rp99452/azure-service-bus-queue-with-net-web-api-and-azure-functions-f026a2de6b7a
author_url
https://medium.com/@rp99452
status
ok
fetched_at
2026-07-15 16:48:10