Azure Service Bus Integration With Asp.NET Core Web API Applications Complete Example Application
Tags: azure, aws, azurefunctions, eventgrid
Published: 2023-08-01 17:09:39

Sure! Below is an example of an ASP.NET Core application named "AzureBusServiceIntegration" that demonstrates how to integrate with Azure Service Bus. This example covers sending and receiving messages using Azure Service Bus Queue.

Step 1: Create a new ASP.NET Core Web Application
Create a new ASP.NET Core Web Application using Visual Studio or the .NET CLI with the following command:
```bash
dotnet new webapp -n AzureBusServiceIntegration
```

Step 2: Install Required NuGet Packages
Add the necessary Azure Service Bus NuGet packages to the project. Open the .csproj file and add the following package references within the `<ItemGroup>` section:

```xml
<ItemGroup>
  <PackageReference Include="Microsoft.Azure.ServiceBus" Version="5.2.1" />
</ItemGroup>
```

Step 3: Configure Azure Service Bus Connection String
In the `appsettings.json` file, add your Azure Service Bus connection string:

```json
{
  "AzureServiceBus": {
    "ConnectionString": "your_service_bus_connection_string",
    "QueueName": "your_queue_name"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  }
}
```

Step 4: Create AzureBusService Class
Create a class named `AzureBusService.cs` to encapsulate the logic for sending and receiving messages from the Azure Service Bus Queue:

```csharp
using System;
using Microsoft.Azure.ServiceBus;
using Microsoft.Extensions.Configuration;
using System.Text;
using System.Threading.Tasks;

namespace AzureBusServiceIntegration.Services
{
    public class AzureBusService : IAzureBusService
    {
        private readonly IConfiguration _configuration;
        private readonly IQueueClient _queueClient;

        public AzureBusService(IConfiguration configuration)
        {
            _configuration = configuration;
            _queueClient = new QueueClient(_configuration["AzureServiceBus:ConnectionString"], _configuration["AzureServiceBus:QueueName"]);
        }

        public async Task SendMessageAsync(string message)
        {
            var encodedMessage = new Message(Encoding.UTF8.GetBytes(message));
            await _queueClient.SendAsync(encodedMessage);
        }

        public async Task ReceiveMessageAsync()
        {
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentCalls = 1,
                AutoComplete = false
            };

            _queueClient.RegisterMessageHandler(ProcessMessageAsync, messageHandlerOptions);
            await Task.CompletedTask; // Let the method run continuously
        }

        private async Task ProcessMessageAsync(Message message, CancellationToken token)
        {
            var messageBody = Encoding.UTF8.GetString(message.Body);
            Console.WriteLine($"Received message: {messageBody}");

            // You can process the message here as per your application's needs.

            await _queueClient.CompleteAsync(message.SystemProperties.LockToken);
        }

        private Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
        {
            Console.WriteLine($"Message handler encountered an exception: {exceptionReceivedEventArgs.Exception}");
            return Task.CompletedTask;
        }
    }
}
```

Step 5: Create the IAzureBusService Interface
Create an interface named `IAzureBusService.cs` to define the methods used in the `AzureBusService` class:

```csharp
using System.Threading.Tasks;

namespace AzureBusServiceIntegration.Services
{
    public interface IAzureBusService
    {
        Task SendMessageAsync(string message);
        Task ReceiveMessageAsync();
    }
}
```

Step 6: Update Startup.cs
In the `Startup.cs` file, configure dependency injection for the `IAzureBusService`:

```csharp
using AzureBusServiceIntegration.Services;

// ...

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddSingleton<IAzureBusService, AzureBusService>();
    // ...
}
```

Step 7: Add Controllers
Create a new controller to send and receive messages. For example, create `HomeController.cs`:

```csharp
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using AzureBusServiceIntegration.Services;

namespace AzureBusServiceIntegration.Controllers
{
    public class HomeController : Controller
    {
        private readonly IAzureBusService _azureBusService;

        public HomeController(IAzureBusService azureBusService)
        {
            _azureBusService = azureBusService;
        }

        public async Task<IActionResult> Index()
        {
            await _azureBusService.SendMessageAsync("Hello, Azure Service Bus!");
            return View();
        }

        public async Task<IActionResult> Receive()
        {
            await _azureBusService.ReceiveMessageAsync();
            return Content("Receiving messages from Azure Service Bus Queue. Check the console output for received messages.");
        }
    }
}
```

Step 8: Add Views
Create a basic view for the `Index` action in `Views/Home/Index.cshtml`:

```html
@{
    ViewData["Title"] = "Home";
}

<h1>Welcome to Azure Service Bus Integration</h1>
<p>Click the button to send a message to Azure Service Bus Queue.</p>
<button type="button" onclick="location.href='@Url.Action("Index", "Home")'">Send Message</button>
```

Step 9: Update `Startup.cs`
Update the `Configure` method in `Startup.cs` to set up routing and add the `Receive` action to receive messages:

```csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using AzureBusServiceIntegration.Services;

namespace AzureBusServiceIntegration
{
    public class Startup
    {
        // ...

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            // ...
            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapControllers();
            });
        }
    }
}
```

Step 10: Run the Application
Run the application, and you can navigate to the `/Home` route to send a message to the Azure Service Bus Queue. To start receiving messages, navigate to the `/Home/Receive` route. The received messages will be printed in the console.