How To Send Queue Message To Azure Service Bus Using ASP.Net Core MVC 6

Introduction

In this article, we will learn how to send queue message to azure service bus using ASP.NET core MVC 6. Before starting this, you can through below article link to understand service bus.

Creating a New Project in Visual Studio 2022

Start Visual Studio software and select Create a new project.

In the Create a new project dialog, select ASP.NET Core Web App (Model-View Controller) > Next.

In the Configure your new project dialog, enter AzureServiceBusCoreMVC6_Demo for Project name. It's important to name the project AzureServiceBusCoreMVC6_Demo. The capitalization needs to match each namespace when code is copied. Select Next.

In the Additional information dialog, select .NET 6.0 (Long-term support). Select Create

The Visual Studio project 2022 will now generate the structure for the selected application. In this example, we are using ASP.Net MVC so we can create a controller to write the code, or so we can use the existing controller. There you can enter the code and build/run the application.

How to Install the Azure.Messaging.ServiceBus Library through NuGet Package Manager

The Visual Studio software provides the Nuget Package manager option to install the package directly to the solution.

In Visual Studio Select Tools > NuGet Package Manager > Manage NuGet Packages for the solution. The below screenshot shows how to open the Nuget Package Manager.

Search for the specific package Azure.Messaging.ServiceBus using the search box on the upper left. Select a package from the list to display its information, enable the Install button and a version-selection drop-down, as shown in the below screenshot. The NuGet package will be installed for your project and reference will be added, as seen in the screenshot below.

In the above image, we can see the list of the related search items. We need to select the required option to install the package to the solution.

On "Visual Studio Solution Explorer" select a file appsettings.json. Open this file and “Add” connection string that you learn from abow article link how to Get the connection string.

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "AzurServiceBusConnectionString": "Endpoint=sb://dotnetazureservicebus.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=H6BXOHp9qVc6yzAvinnF6ZoQBn1iCMHvOzFLz7UBzcA="
  }
}

On "Visual Studio Solution Explorer" Create a folder ServiceBus and in that add an Interface IServiceBusQueue.cs

using Azure.Messaging.ServiceBus;
namespace AzureServiceBusCoreMVC6_Demo.ServiceBus {
    public interface IServiceBusQueue {
        Task SendMessageAsync(string serviceBusMessage);
    }
}

Now create a class ServiceBusQueue and implement IServiceBusQueue

using Azure.Messaging.ServiceBus;
namespace AzureServiceBusCoreMVC6_Demo.ServiceBus {
    public class ServieBusQueue: IServiceBusQueue {
        private readonly IConfiguration _configuration;
        public ServieBusQueue(IConfiguration configuration) {
            _configuration = configuration;
        }
        public async Task SendMessageAsync(string serviceBusMessage) {
            try {
                string queueName = "myqueue";
                ServiceBusClient serviceBusClient = new ServiceBusClient(_configuration.GetConnectionString("AzurServiceBusConnectionString"), new ServiceBusClientOptions() {
                    TransportType = ServiceBusTransportType.AmqpWebSockets
                });
                ServiceBusSender serviceBusSender = serviceBusClient.CreateSender(queueName);
                await serviceBusSender.SendMessageAsync(new ServiceBusMessage(serviceBusMessage));
            } catch (Exception) {
                throw;
            }
        }
    }
}

On "Visual Studio Solution Explorer" select a file Program.csAdd” below service.

builder.Services.AddSingleton<IServiceBusQueue, ServieBusQueue>();

On "Visual Studio Solution Explorer" in controllers folder select HomeController and “Add” below code.

using AzureServiceBusCoreMVC6_Demo.ServiceBus;
using Microsoft.AspNetCore.Mvc;
namespace AzureServiceBusCoreMVC6_Demo.Controllers {
    public class HomeController: Controller {
        private readonly IServiceBusQueue _serviceBusQueue;
        public HomeController(IServiceBusQueue serviceBusQueue) {
            _serviceBusQueue = serviceBusQueue;
        }
        public IActionResult Index() {
                return View();
            }
            [HttpPost]
        public async Task < IActionResult > Index(string message) {
            await _serviceBusQueue.SendMessageAsync(message);
            ViewBag.SuccessMessage = "Message has been sent successfully..";
            return View();
        }
    }
}

On "Visual Studio Solution Explorer" in Views folder open Home folder select Index.cshtml file and paste below code.

@{
    ViewData["Title"] = "Home Page";
}

<div class="text-center">
       <form asp-action="Index">
        <div class="mb-3">
            <label for="exampleFormControlTextarea1" class="form-label">Message</label>
            <textarea class="form-control" id="message" name="message" rows="3"></textarea>
        </div>
        <input type="submit" value="Send Queue Message" class="btn btn-success" />
    </form> 
    <strong class="alert-success">@ViewBag.SuccessMessage</strong>
</div>

Now it’s time build and Run your project ctrl+F5

Conclusion

In this article, we have learned how to send queue message to azure service bus using ASP.NET Core MVC6. I hope you enjoyed the article. Happy coding