Home > Software engineering >  Get message id from Azure Service Bus Queue in .net 5
Get message id from Azure Service Bus Queue in .net 5

Time:10-27

I want to send a message to a service bus queue and receive it's ID.

The sdk examples seems to provide a solution.

string connectionString = "<connection_string>";
string queueName = "<queue_name>";
// since ServiceBusClient implements IAsyncDisposable we create it with "await using"
await using var client = new ServiceBusClient(connectionString);

// create the sender
ServiceBusSender sender = client.CreateSender(queueName);

// create a message that we can send. UTF-8 encoding is used when providing a string.
ServiceBusMessage message = new ServiceBusMessage("Hello world!");

// send the message
await sender.SendMessageAsync(message);

// create a receiver that we can use to receive the message
ServiceBusReceiver receiver = client.CreateReceiver(queueName);

// the received message is a different type as it contains some service set properties
ServiceBusReceivedMessage receivedMessage = await receiver.ReceiveMessageAsync();

string id = receivedMessage.Id

The ReceiveMessageAsync() will return the first item in the queue, so how can I be sure that another message won't arrive to the queue (from another client) between sending the message

await sender.SendMessageAsync(message);

and receiving it

await receiver.ReceiveMessageAsync();

CodePudding user response:

You can set the identifier of a given ServiceBusMessage through the MessageId property:

The message identifier is an application-defined value that uniquely identifies the message and its payload. The identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. If enabled, the duplicate detection feature identifies and removes second and further submissions of messages with the same MessageId.

Just define the identifier as a GUID and save the value. No additional complexity is needed.

More information:

ServiceBusMessage.MessageId Property

  • Related