Thanks for posting your question in the Microsoft Q&A forum.
Here's an example of how you can send and receive messages:
- Install the Azure.Messaging.ServiceBus NuGet package in your ASP.NET Core project.
- In your Startup.cs file, add the following code to register the ServiceBusClient as a singleton service:
public void ConfigureServices(IServiceCollection services) { services.AddSingleton(serviceProvider => { var connectionString = Configuration.GetConnectionString("ServiceBusConnectionString"); return new ServiceBusClient(connectionString); }); }
- Create a new class, for example,
ServiceBusQueueService.cs
, and implement the logic for sending and receiving messages:using Azure.Messaging.ServiceBus; public class ServiceBusQueueService { private readonly ServiceBusClient _serviceBusClient; private readonly string _queueName = "myqueue"; public ServiceBusQueueService(ServiceBusClient serviceBusClient) { _serviceBusClient = serviceBusClient; } public async Task SendMessageAsync(string message) { var sender = _serviceBusClient.CreateSender(_queueName); var serviceBusMessage = new ServiceBusMessage(message); await sender.SendMessageAsync(serviceBusMessage); } public async Task ReceiveMessagesAsync() { var receiver = _serviceBusClient.CreateReceiver(_queueName); var messages = await receiver.ReceiveMessagesAsync(maxMessages: 10); foreach (var message in messages) { Console.WriteLine($"Received message: {message.Body}"); await receiver.CompleteMessageAsync(message); } } }
- In your controller or service where you want to send or receive messages, inject the
ServiceBusQueueService
and call the respective methods:
public class MyController : Controller
{
private readonly ServiceBusQueueService _serviceBusQueueService;
public MyController(ServiceBusQueueService serviceBusQueueService)
{
_serviceBusQueueService = serviceBusQueueService;
}
public async Task<IActionResult> SendMessage(string message)
{
await _serviceBusQueueService.SendMessageAsync(message);
return Ok();
}
public async Task<IActionResult> ReceiveMessages()
{
await _serviceBusQueueService.ReceiveMessagesAsync();
return Ok();
}
}
Please don't forget to close up the thread here by upvoting and accept it as an answer if it is helpful