Integrating Azure Service Bus with .NET Applications

Set up Azure Service Bus and build .NET message producers, scheduled messages, and an Azure Function consumer for asynchronous workflows.

Integrating Azure Service Bus with .NET Applications cover

Introduction

Azure Service Bus is a Microsoft Azure messaging service that enables asynchronous communication between applications and services. It is useful when you want to decouple components and build scalable systems that process messages reliably.

What We Will Cover

This article covers:

  • Setting up Azure Service Bus in the Azure portal
  • Creating queues inside the Service Bus
  • Building .NET APIs to send messages
  • Scheduling and canceling scheduled messages
  • Creating an Azure Function to receive messages

1. Set Up Azure Service Bus in the Azure Portal

Step 1

Go to the Azure portal.

Step 2

Search for Service Bus and open the service.

Search for Service Bus

Step 3

Click Create.

Create Service Bus

Step 4

Provide the basic details.

The article uses these settings:

  • Subscription
  • Resource Group
  • Namespace
  • Location
  • Pricing Tier

Basic Service Bus details

Pricing Options

The portal shows pricing options such as Basic, Standard, and Premium.

Pricing options

Advanced Options

Step 5: Additional Options

The Advanced tab includes settings like minimum TLS and local authentication.

Advanced Service Bus options

Step 6: Networking

Keep the default networking settings unless you have specific requirements.

Networking settings

Step 7: Review + Create

Review the details and click Create.

Review and create

2. Set Up Queues in the Service Bus

Step 1

Select Queue from the Entity menu.

Select queue entity

Step 2

Click New Queue.

Step 3

Provide queue details such as name, maximum size, delivery count, TTL, and lock duration.

Queue details

Step 4

Create the queue.

3. Create a .NET API to Send Messages

Install Packages

Install these NuGet packages:

  • Azure.Messaging.ServiceBus
  • Newtonsoft.Json

Get the Connection String

Go to Shared Access Policies and open RootManageSharedAccessKey.

Get Service Bus connection string

Store the connection string and queue name in app settings.

Store settings

Controller for Sending Messages

using API.Models; using Azure.Messaging.ServiceBus; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace API.Controllers; [Route("api/[controller]/[action]")] [ApiController] public class ServiceBusController : ControllerBase { readonly IConfiguration _configuration; public ServiceBusController(IConfiguration configuration) { _configuration = configuration; } [HttpPost] public async Task<IActionResult> SendMessageAsync([FromBody] EmployeeModel employee) { string connectionString = _configuration.GetValue<string>("ServiceBusSettings:ConnectionString"); string queueName = _configuration.GetValue<string>("ServiceBusSettings:QueueName"); var client = new ServiceBusClient(connectionString); var sender = client.CreateSender(queueName); string body = JsonConvert.SerializeObject(employee); var message = new ServiceBusMessage(body); await sender.SendMessageAsync(message); return Ok("Message sent to the Service Bus queue successfully"); } }

Employee Model

namespace API.Models; public class EmployeeModel { public string FirstName { get; set; } public string LastName { get; set; } public string Designation { get; set; } public string Department { get; set; } public string Note { get; set; } }

Explanation

  • Inject IConfiguration in the controller
  • Read the connection string and queue name from app settings
  • Create a ServiceBusClient
  • Create a sender with CreateSender
  • Serialize the model to JSON and send it as a ServiceBusMessage

Use Dependency Injection for Service Bus Client

Register the client in Program.cs.

builder.Services.AddSingleton<ServiceBusClient>( new ServiceBusClient(builder.Configuration.GetValue<string>("ServiceBusSettings:ConnectionString")) );

Use the injected client and create the sender in the controller constructor if you want to reuse one queue.

4. Schedule and Cancel Messages

Schedule a Message

[HttpPost] public async Task<IActionResult> ScheduleMessageAsync([FromBody] EmployeeModel employee) { string body = JsonConvert.SerializeObject(employee); var message = new ServiceBusMessage(body); message.ScheduledEnqueueTime = DateTimeOffset.UtcNow.AddMinutes(5); long sequenceNumber = await _serviceBusSender.ScheduleMessageAsync(message, message.ScheduledEnqueueTime); return Ok($"Message scheduled to the Service Bus queue successfully. Sequence number: {sequenceNumber}"); }

Cancel a Scheduled Message

[HttpPost] public async Task<IActionResult> CancelScheduledMessageAsync([FromQuery] long sequenceNumber) { await _serviceBusSender.CancelScheduledMessageAsync(sequenceNumber); return Ok($"Scheduled message with sequence number {sequenceNumber} has been canceled."); }

5. Create an Azure Function to Receive Messages

Create the Function Project

Create a new Azure Function project and choose the Azure Service Bus Queue Trigger template.

Create Azure Function

Service Bus Connection Settings

Add these values to local.settings.json.

{ "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "UseDevelopmentStorage=true", "FUNCTIONS_WORKER_RUNTIME": "dotnet", "ServiceBusConnectionString": "YOUR_SERVICE_BUS_CONNECTION_STRING", "QueueName": "YOUR_QUEUE_NAME" } }

Function Logic

using Azure.Messaging.ServiceBus; using Microsoft.Azure.Functions.Worker; using Microsoft.Extensions.Logging; namespace ServiceBusReceiver; public class TestQueueReceiver(ILogger<TestQueueReceiver> logger) { [Function(nameof(TestQueueReceiver))] public async Task Run( [ServiceBusTrigger("%QueueName%", Connection = "ServiceBusConnectionString")] ServiceBusReceivedMessage message, ServiceBusMessageActions messageActions) { logger.LogInformation("Message ID: {id}", message.MessageId); logger.LogInformation("Message Body: {body}", message.Body); logger.LogInformation("Message Content-Type: {contentType}", message.ContentType); await messageActions.CompleteMessageAsync(message); } }

The function logs the incoming message and marks it complete so it is removed from the queue.

Output

Service Bus receiver output

Conclusion

Azure Service Bus, together with .NET, provides a solid messaging platform for scalable and resilient applications. By combining queues with Azure Functions triggers, you can implement asynchronous communication and workflow automation effectively.

The original article links to the source code on GitHub: AzureServiceBus.