See the source code for this sample in this github repo: https://github.com/luiscoco/Azure_ServiceBus_with_dotNET8_WebAPI_producer
We first log in to Azure Portal and search for Azure Service Bus
We create a new Azure Service Bus
We input the required data: Subscription, ResourceGroup, Namespace, location and pricing tier
We verify the new Azure Service Bus
We get the connection string
This is the connection string:
Endpoint=sb://myservicebus1974.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=c/7ve5kw9QuPqM8YSUWQvNTrjM+y5hkmp+ASbE85qY4=
We have to create a new topic
Creating a .NET 8 Web API using Visual Studio Code (VSCode) and the .NET CLI is a straightforward process
This guide assumes you have .NET 8 SDK, VSCode, and the C# extension for VSCode installed. If not, you'll need to install these first
Step 1: Install .NET 8 SDK
Ensure you have the .NET 8 SDK installed on your machine: https://dotnet.microsoft.com/es-es/download/dotnet/8.0
You can check your installed .NET versions by opening a terminal and running:
dotnet --list-sdks
If you don't have .NET 8 SDK installed, download and install it from the official .NET download page
Step 2: Create a New Web API Project
Open a terminal or command prompt
Navigate to the directory where you want to create your new project
Run the following command to create a new Web API project:
dotnet new webapi -n ServiceBusSenderApi
This command creates a new directory with the project name, sets up a basic Web API project structure, and restores any necessary packages
Step 3: Open the Project in VSCode
Once the project is created, you can open it in VSCode by navigating into the project directory and running:
code .
This command opens VSCode in the current directory, where . represents the current directory
We run this command to add the Azure Service Bus library
dotnet add package Azure.Messaging.ServiceBus
We also have to add the Swagger and OpenAPI libraries to access the API Docs
This is the csproj file including the project dependencies
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus;
using Microsoft.AspNetCore.Mvc;
namespace ServiceBusSenderApi.Controllers
{
public class MessageDto
{
public string? Body { get; set; }
public string? Priority { get; set; }
}
[ApiController]
[Route("api/[controller]")]
public class ServiceBusController : ControllerBase
{
private static string connectionString = "Endpoint=sb://myservicebus1974.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=c/7ve5kw9QuPqM8YSUWQvNTrjM+y5hkmp+ASbE85qY4=";
private static string topicName = "mytopic";
private static ServiceBusClient client;
private static ServiceBusSender sender;
static ServiceBusController()
{
client = new ServiceBusClient(connectionString);
sender = client.CreateSender(topicName);
}
[HttpPost("send")]
public async Task<ActionResult> SendMessage([FromBody] MessageDto messageDto)
{
var message = new ServiceBusMessage(messageDto.Body)
{
ApplicationProperties =
{
["priority"] = messageDto.Priority
}
};
await sender.SendMessageAsync(message);
return Ok($"Sent message: {messageDto.Body}, Priority: {messageDto.Priority}");
}
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Add Swagger
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "ServiceBusSenderApi", Version = "v1" });
});
var app = builder.Build();
// Configure the HTTP request pipeline.
app.UseRouting();
// Enable middleware to serve generated Swagger as a JSON endpoint.
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "ServiceBusSenderApi v1");
});
app.UseAuthorization();
app.MapControllers();
app.Run();
We execute this command to run the application
dotnet run
We navigate to the application endpoint: http://localhost:5256/swagger/index.html
After executing the above request we get this response
We confirm in the Azure Service Bus we recevied the message
We navigate to the subscription and see the received message
See also the custom message property we added to the message