Azure  

Azure service bus integration with .NET 8 - Read & Write

In this article, we will discuss the Azure Service Bus, how to configure it in the Azure Portal, and how to create a .NET Core Web API to send and receive messages from a queue.

Agenda

  • What is Azure Service Bus?

  • Configure the Azure Service Bus on the Azure portal.

  • Create a web API to enqueue the message.

  • Create a Web API to read the message from the queue.

What is Azure Service Bus?

Microsoft Azure Service Bus is a cloud-based message broker that enables asynchronous communication between applications.

It helps in:

  • Decoupling sender and receiver applications

  • Improving reliability

  • Supporting distributed systems

  • Handling high-volume message traffic

In simple words:

Instead of Application A directly calling Application B, it sends a message to the Service Bus. Application B reads it whenever it is ready.

This makes the system loosely coupled and scalable.

sb-queues-08

Types of Azure Service Bus (High level)

In Azure Service Bus we can work with three types of messaging entities.

  1. Queue (point to point)

  2. Topic (publish - subscribe)

  3. Subscription (Child of Topic)

  • Queue (point to point)

One message -> processed by only ONE consumer. Multiple consumers can exist, but only one receives each message

Producer → Queue → Consumer

  • Topic (publish - subscribe)

One message → delivered to MULTIPLE consumers. Multiple consumers can exist, and each message serves to each and every consumer.

Producer → Topic
→ Subscription A → Consumer A
→ Subscription B → Consumer B

  • Subscription (Child of Topic)

A subscription acts as a logical receiver inside a topic. Each subscription behaves like a virtual queue.

Configure Azure Service Bus in Azure Portal

Step 1: Create Namespace

  1. Go to Azure Portal

  2. Click Create Resource

  3. Search for Azure Service Bus

    s1
  4. Click Create

  5. Provide:

    • Subscription

    • Resource Group

    • Namespace Name

    • Pricing Tier (Basic / Standard / Premium)

    s5

Step 2: Create a Queue

  1. Open your Namespace

  2. Click Queues

  3. Click + Queue

  4. Provide queue name

  5. Click Create

    s7
  6. If you want you can send a sample message. Write the message in message body; keep everything else as it is and click send.

    s10
  7. Now you can seen the message, which is available in the queue.

    s12

Step 3: Get Connection String

  1. Go to Namespace

  2. Click Shared Access Policies

  3. Click RootManageSharedAccessKey

  4. Copy Primary Connection String

    s13

Create .NET Core Web API

  • Open Visual Studio and create a new project ASP.NET Core Web API.

Step 1: Install NuGet Package

dotnet add package Azure.Messaging.ServiceBus

Step 2: Add Configuration in appsettings.json

{
  "ServiceBus": {
    "ConnectionString": "YOUR_CONNECTION_STRING",
    "QueueName": "samplequeue"
  }
}

Step 3: Update program.cs file

using AzureServiceBus.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<ServiceBusSenderService>();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Step 4: Create ServiceBusSenderService Service class

using Azure.Messaging.ServiceBus;

namespace AzureServiceBus.Services
{
    public class ServiceBusSenderService
    {
        private readonly ServiceBusSender _sender;
        private readonly ServiceBusReceiver _receiver;

        public ServiceBusSenderService( IConfiguration config)
        {
            var connectionString = config["ServiceBus:ConnectionString"];
            var queueName = config["ServiceBus:QueueName"];

            var client = new ServiceBusClient(connectionString);
            _sender = client.CreateSender(queueName);
            _receiver = client.CreateReceiver(queueName);

        }

        public async Task SendMessageAsync(string messageBody)
        {
           var message = new ServiceBusMessage(messageBody);
            // Optional metadata
            message.ApplicationProperties["Source"] = "WebAPI"; 
            await _sender.SendMessageAsync(message);
        }

        public async Task<string> ReceiveMessagesAsync()
        {
            var message = await _receiver.ReceiveMessageAsync(
                TimeSpan.FromSeconds(5)
                );
            if(message == null)
            {
                Console.WriteLine("No messages received.");
                return null;
            }
            string body = message.Body.ToString();
            await _receiver.CompleteMessageAsync(message); 
            return body;
        }
    }
}

Step 5: Create Controller to Send Message and Receive Message from the Queue


using AzureServiceBus.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace AzureServiceBus.Controllers
{
    
    [ApiController]
    [Route("api/messages")]
    public class MessageController : ControllerBase
    {
        private readonly ServiceBusSenderService _service;

        public MessageController(ServiceBusSenderService service)
        {
            _service = service;
        }

        [HttpPost]
        public async Task<IActionResult> SendMessage([FromBody] string message)
        {
            await _service.SendMessageAsync(message);
            return Ok(new { Status = "Message sent successfully" });
        }
        [HttpGet]
        public async Task<IActionResult> ReceiveMessage()
        {
            var message = await _service.ReceiveMessagesAsync();
            if (message == null)
            {
                return NotFound(new { Status = "No messages available" });
            }
            return Ok(new { Status = "Message received successfully", Message = message });
        }

    }
}

Send Message to Queue

  • Call the API and send your message in request body

    s14
  • You can see the message inside Service Bus Explorer.

    s15

    Read Message from the Queue

  • Read the message from the queue. Call GET API

    s16

    Conclusion

    Azure Service Bus is a powerful cloud messaging system that

    • Enables asynchronous communication

    • Decouples services

    • Improves scalability

    • Supports microservice architecture

    Using .NET Core Web API, we can easily integrate Service Bus for sending and receiving messages.

Thank you so much for reading this article. Happy coding!!