gpt4 book ai didi

c# - 如何在azure服务总线命名空间中创建主题、订阅和SAS策略?

转载 作者:行者123 更新时间:2023-12-03 01:27:00 25 4
gpt4 key购买 nike

我需要使用共享访问策略连接字符串为 azure 服务总线命名空间创建主题、订阅和 SAS 策略。为此,我使用了“Microsoft.Azure.ServiceBus”NuGet 包。(我使用这个 NuGet 包是因为我使用的是 .NET Core 2.1)。

注意:- 命名空间已在 Azure 服务总线中创建。

我尝试过的:-

现在,我可以使用以下代码创建主题和订阅

 public static async Task CreateTopicSubscriptionAndSASPolicy()
{
string ServiceBusConnectionString = "Endpoint=sb://servicebusnameone.servicebus.windows.net/;SharedAccessKeyName=xxxxx;xxxxxxxxxxxxxxxxxxxxxxx";
string topic = "TopicOne";
string subscriptionName = "SubOne";
var client = new ManagementClient(ServiceBusConnectionString);

if (!await client.TopicExistsAsync(topic))
{
await client.CreateTopicAsync(topic);
}
if (!await client.SubscriptionExistsAsync(topic, subscriptionName))
{
await client.CreateSubscriptionAsync(new SubscriptionDescription(topic, subscriptionName));
}

IEnumerable<AccessRights> accessRights = new[] { AccessRights.Send };
SharedAccessAuthorizationRule sharedAccessAuthorizationRule = new SharedAccessAuthorizationRule("SendRule", accessRights);
//TO DO Create SAS Policy....
}

现在,我需要在命名空间级别创建 SAS 策略,但我不确定如何做到这一点?我还阅读了以下 Microsoft 文档和 stackoverflow 问题解答

  1. https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-sas

  2. https://github.com/Huachao/azure-content/blob/master/articles/service-bus/service-bus-shared-access-signature-authentication.md

  3. Shared Access Policy Programatic Creation for Azure Service Bus

  4. Using SAS Token with Azure ServiceBus

  5. Azure Service Bus Shared Access Signature Generation

问题:-

  1. 如何在 Azure 服务总线命名空间中创建 SAS 策略?
  2. 有什么方法可以在创建时配置主题/订阅吗? (因为当我使用上面给定的代码创建主题时,它创建的主题最大大小为 1024 MB,但我需要将其设置为 5120 MB)?
  3. 除此之外,还有什么更好的方法(最佳实践)来使用 .Net Core 2.1 中的连接字符串创建主题、订阅和 SAS 策略?

注意:- 任何工作示例都非常有助于清晰理解。

最佳答案

更新2020/12/22

我检查了所有主要包的源代码,没有办法使用这些包创建基于命名空间的访问策略,只能在实体上创建。

所以,让我们遵循一个更基本的方式,使用rest API(这些包的底层逻辑也是基于此。)。

下面是代码,在我这边运行良好:

using Microsoft.Azure.Services.AppAuthentication;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp23
{
class Program
{
static void Main(string[] args)
{
CallWebAPIAsync().Wait();
}

static async Task CallWebAPIAsync()
{
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/").Result;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
client.BaseAddress = new Uri("https://management.azure.com/");


client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//PUT Method
var jsonString = "{ \"properties\": { \"rights\": [ \"Listen\", \"Send\", \"Manage\" ] } }";
var httpContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PutAsync("https://management.azure.com/subscriptions/e5b0xxxxxx9f4c68/resourceGroups/0730BowmanWindow/providers/Microsoft.ServiceBus/namespaces/bowman1012/AuthorizationRules/testbowman?api-version=2017-04-01",httpContent);
if (response.IsSuccessStatusCode)
{
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}
else
{
Console.WriteLine("Internal server Error");
}
}
}
}
}

效果很好:

enter image description here

以下是其余API引用,如有疑问请告诉我。

https://learn.microsoft.com/en-us/rest/api/servicebus/stable/namespaces%20-%20authorization%20rules/createorupdateauthorizationrule

更新:

.csproj 文件

<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>

<ItemGroup>

<PackageReference Include="Azure.Messaging.ServiceBus" Version="7.0.0" />

<PackageReference Include="Microsoft.Azure.ServiceBus" Version="5.1.0" />
</ItemGroup>

</Project>

Program.cs

using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Primitives;
using Azure.Messaging.ServiceBus.Administration;
using System;
using System.Text;

namespace ConsoleApp15
{
class Program
{
static async System.Threading.Tasks.Task Main(string[] args)
{
string keyname = "test";
string sharedaccesskey = "xxxxxx";
var validityDuration = TimeSpan.FromHours(24);
TokenScope tokenScope = TokenScope.Entity;

//Get the SAS based on the namespace.
var tokenprovider =(SharedAccessSignatureTokenProvider) TokenProvider.CreateSharedAccessSignatureTokenProvider(keyname,sharedaccesskey,validityDuration,tokenScope);
var token =await tokenprovider.GetTokenAsync("sb://bowman1012.servicebus.windows.net/", TimeSpan.FromHours(24));

//Send message to service bus queue based on SAS token.
ServiceBusConnectionStringBuilder builder = new ServiceBusConnectionStringBuilder {
Endpoint= "sb://bowman1012.servicebus.windows.net/",
EntityPath= "testbowman",
SasToken= token.TokenValue
};
QueueClient client = new QueueClient(builder);
Message mes = new Message();
mes.Body = Encoding.ASCII.GetBytes("This is a test.20201208");
await client.SendAsync(mes);

//Create a topic with 5120MB.
var client1 = new ServiceBusAdministrationClient("Endpoint=sb://bowman1012.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xxxxxx");
var topicOptions = new CreateTopicOptions("20201208")
{
AutoDeleteOnIdle = TimeSpan.FromDays(7),
DefaultMessageTimeToLive = TimeSpan.FromDays(2),
DuplicateDetectionHistoryTimeWindow = TimeSpan.FromMinutes(1),
EnableBatchedOperations = true,
EnablePartitioning = false,
MaxSizeInMegabytes = 5120,
RequiresDuplicateDetection = true,
UserMetadata = "some metadata"
};
topicOptions.AuthorizationRules.Add(new SharedAccessAuthorizationRule(
"allClaims",
new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen }));
await client1.CreateTopicAsync(topicOptions);


Console.WriteLine("Hello World!" + "\n" + token.TokenValue);
}
}
}

在我这边工作得很好:

enter image description here

enter image description here

<小时/>

原始答案:

How can I create SAS policy in azure service bus namespace?

您可以使用SharedSecretTokenProvider.BuildKey(string applyTo, string action)方法创建SAS。

这是 API 引用:

https://learn.microsoft.com/en-us/dotnet/api/microsoft.servicebus.sharedaccesssignaturetokenprovider?view=azure-dotnet

或者你可以引用这个文档(一些简单的代码):

https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-sas#use-shared-access-signature-authorization

There is any way to configure topic/subscriptions while creating?(because while I create topic using above given code it create topicwith Max size 1024 MB but I need to set it 5120 MB)?

使用NamespaceManager.CreateTopic方法,该方法返回TopicDescription对象,您可以通过MaxSizeInMegabytes属性设置大小(以兆字节为单位)。

这是 API 引用:

https://learn.microsoft.com/en-us/dotnet/api/microsoft.servicebus.namespacemanager.createtopic?view=azure-dotnet

https://learn.microsoft.com/en-us/dotnet/api/microsoft.servicebus.messaging.topicdescription.maxsizeinmegabytes?view=azure-dotnet#Microsoft_ServiceBus_Messaging_TopicDescription_MaxSizeInMegabytes

除此之外,还有什么更好的方法(最佳实践)来使用 .Net Core 2.1 中的连接字符串创建主题、订阅和 SAS 策略?

我不确定您在这一点上担心什么,也许您可​​以解释一下您在寻找什么?上述官方文档提供了这种获取方法。

以及创建订阅的方法:

https://learn.microsoft.com/en-us/dotnet/api/microsoft.servicebus.namespacemanager.createsubscription?view=azure-dotnet

关于c# - 如何在azure服务总线命名空间中创建主题、订阅和SAS策略?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65194186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com