我最终使用了以下ServiceBusConnectionStringBuilder
使用 SharedAccess 签名的覆盖:
public ServiceBusConnectionStringBuilder (string endpoint, string entityPath, string sharedAccessSignature);
基于此,这是我编写的代码。这首先会生成一个RootManagedAccessKey
有效期为一小时的 SAS 令牌,然后使用该令牌将消息发送到队列。
using System;
using System.Text;
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Primitives;
namespace SO60273377
{
class Program
{
static void Main(string[] args)
{
var endpoint = "sb://<namespace>.servicebus.windows.net/";
var queueName = "test";
var keyName = "RootManageSharedAccessKey";
var keyValue = "<key>";
var validityDuration = TimeSpan.FromHours(1);
TokenScope tokenScope = TokenScope.Entity;
var provider = (SharedAccessSignatureTokenProvider) TokenProvider.CreateSharedAccessSignatureTokenProvider(keyName, keyValue, validityDuration, tokenScope);
var token = provider.GetTokenAsync(endpoint+queueName, validityDuration).GetAwaiter().GetResult();
var sasToken = token.TokenValue;
Console.WriteLine("SAS Token: " + sasToken);
var serviceBusConnectionStringBuilder = new ServiceBusConnectionStringBuilder(endpoint, queueName, sasToken);
QueueClient client = new QueueClient(serviceBusConnectionStringBuilder, ReceiveMode.PeekLock);
client.SendAsync(new Message(Encoding.UTF8.GetBytes("This is a test"))).GetAwaiter().GetResult();
Console.WriteLine("Press any key to continue");
Console.ReadLine();
}
}
}