Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

This article will discuss the Azure Service Bus introduction and its implementation using .NET Core 6 Web API. Also, the queue trigger is listening to the service bus and receiving the messages.

Agenda

  • Introduction
  • Azure Service Bus
  • Step-by-step Implementation
  • Service Bus Queue Trigger

Prerequisites

  • Visual Studio 2022
  • .NET Core 6
  • Azure Account

Introduction

  • Azure Service Bus is a fully managed messaging cloud service and different types of applications can communicate with each other via a message queue.
  • Message can transfer between the different applications and it includes metadata about the message and the encoded information in different formats like JSON or XML.

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

  • Sometimes, there are different senders sending the message and that will get stored inside the service bus queue we can store any number of messages depending upon the storage size which we have.
  • On the other side, Receivers listen to the message queue continuously and get the corresponding messages as per their topic, queue, and subscription.

Azure Service Bus

Step 1

Open the Azure portal and search for the service bus.

Step 2

Click on create and fill in the required information.

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step 3

Open the service bus which we created and go to the shared access policy section inside that we can find our primary connection string which we use inside the web application.

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step 4

Next, go to the Queue section and create a new queue.

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step 5

Open the queue and here we can see at this moment active message count is zero.

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step-by-step Implementation

Step 1

Create a new .NET Core Web API project.

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step 2

Configure the new project

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step 3

Provide additional information

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step 4

Project Structure

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step 5

Install the following NuGet packages

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step 6

Create a new Car Details class

namespace AzureServiceBusDemo.Models
{
    public class CarDetails
    {
        public int CarId { get; set; }
        public string CarModel { get; set; }
        public string Price { get; set; }
        public string Status { get; set; }
    }
}

Step 7

Next, add IServiceBus Repository and ServiceBus implementation class.

IServiceBus

using AzureServiceBusDemo.Models;
using System;
namespace AzureServiceBusDemo.Repositories {
    public interface IServiceBus {
        Task SendMessageAsync(CarDetails carDetails);
    }
}

ServiceBus

using System.Text.Json;
using System.Text;
using AzureServiceBusDemo.Models;
using Microsoft.Azure.ServiceBus;
namespace AzureServiceBusDemo.Repositories {
    public class ServiceBus: IServiceBus {
        private readonly IConfiguration _configuration;
        public ServiceBus(IConfiguration configuration) {
            _configuration = configuration;
        }
        public async Task SendMessageAsync(CarDetails carDetails) {
            IQueueClient client = new QueueClient(_configuration["AzureServiceBusConnectionString"], _configuration["QueueName"]);
            //Serialize car details object
            var messageBody = JsonSerializer.Serialize(carDetails);
            //Set content type and Guid
            var message = new Message(Encoding.UTF8.GetBytes(messageBody)) {
                MessageId = Guid.NewGuid().ToString(),
                    ContentType = "application/json"
            };
            await client.SendAsync(message);
        }
    }
}

Step 8

Open the appsettings.json file and add the azure service bus connection string and queue name.

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft.AspNetCore": "Warning"
        }
    },
    "AllowedHosts": "*",
    "AzureServiceBusConnectionString": "",
    "QueueName": "jdlearningqueue "
}

Step 9

Register a few services inside the Program class as I showed below.

using AzureServiceBusDemo.Repositories;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddScoped < IServiceBus, ServiceBus > ();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
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 10

Create a new Car Details controller.

using AzureServiceBusDemo.Models;
using AzureServiceBusDemo.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace AzureServiceBusDemo.Controllers {
    [Route("api/[controller]")]
    [ApiController]
    public class CarsController: ControllerBase {
        private readonly IServiceBus _serviceBus;
        public CarsController(IServiceBus serviceBus) {
            _serviceBus = serviceBus;
        }
        /// <summary>
        /// Send Order Details
        /// </summary>
        /// <param name="carDetails"></param>
        /// <returns></returns>
        [HttpPost("OrderDetails")]
        public async Task < IActionResult > OrderDetails(CarDetails carDetails) {
            if (carDetails != null) {
                await _serviceBus.SendMessageAsync(carDetails);
            }
            return Ok();
        }
    }
}

Step 11

Build and run the application

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Service Bus Queue Trigger

  • Azure service bus trigger is used to respond to messages which are present inside the service bus queue and topic.

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

  • We send the message using Web API to the queue and after that service bus queue trigger function received the corresponding message which is present inside the queue and sent by the sender.
  • There are different types of triggers available in azure if we want to send messages inside the azure function that is also possible. Here, we use Web API as the sender application.

Let’s create the Azure Service Bus Queue Trigger

Step 1

Create a new Azure function project.

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step 2

Configure a new project.

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step 3

Provide the additional information like connection string name, queue name, and type of function trigger.

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step 4

Open and add the azure service bus connection string inside the local.settings.json file.

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

Step 5

Add the following code inside the function class. We can modify it as per the requirement if we want to process some messages and perform some action using that. here, we just fetch and add display messages for demo purposes.

using System;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
namespace ServiceBusTrigger {
    public class Function1 {
        [FunctionName("Function1")]
        public void Run([ServiceBusTrigger("jdlearningqueue", Connection = "ServiceBusConnectionString")] string myQueueItem, ILogger log) {
            log.LogInformation($ "C# ServiceBus queue trigger function processed message: {myQueueItem}");
        }
    }
}

Step 6

Run the function trigger project.

Step 7

Send some messages by using swagger UI which we implement in Web API.

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step 8

Open the azure portal and here we can see 1 active message is available.

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

Step 9

On the other side in the function application console. We can see the messages which we sent earlier by using Web API.

Azure Service Bus implementation using .NET Core 6 and Queue Trigger to fetch messages

So, this is all about Azure Service Bus and Its function trigger.

GitHub Link

https://github.com/Jaydeep-007/AzureServiceBusDemo

Conclusion

Here we discuss the introduction of the service bus and its trigger function. Also, the step-by-step implementation and configuration using .NET Core 6 Web API and Azure.


Recommended Ebook

The Developer’s Guide to Microsoft Azure - Second Edition

Download Now!
Similar Articles