gpt4 book ai didi

c# - 使用 Microsoft.Azure.WebJobs.Extensions.ServiceBus 5.5.1 以编程方式设置连接字符串

转载 作者:行者123 更新时间:2023-12-03 04:40:37 28 4
gpt4 key购买 nike

我正在为一个 webjob-project 升级 nuget-packages,该项目使用 4.3.0 版本的 Microsoft.Azure.WebJobs.Extensions.ServiceBus,其中连接字符串可以通过编程方式设置,如下所示:

.ConfigureWebJobs(b =>
{
b.AddServiceBus(options =>
{
options.ConnectionString = connectionString;
});
})

效果很好。我们将连接字符串存储在 Azure Key Vault 中,而不是应用程序设置文件中。

但是,升级到5.5.1后,没有设置连接字符串的选项。

还有其他方法可以设置吗?在触发器本身上,您只能指定 appsettings.json 中的设置名称。

https://github.com/Azure/azure-sdk-for-net/blob/Microsoft.Azure.WebJobs.Extensions.ServiceBus_5.5.1/sdk/servicebus/Microsoft.Azure.WebJobs.Extensions.ServiceBus/src/Config/ServiceBusOptions.cs

托管身份可用于避免设置文件中的 secret ,但此特定项​​目尚未在 Azure 中针对服务总线进行配置,我更愿意保留当前的解决方案,直到我们可以为所有连接使用托管身份立刻。

封装:https://www.nuget.org/packages/Microsoft.Azure.WebJobs.Extensions.ServiceBus

文档: https://github.com/Azure/azure-sdk-for-net/blob/Microsoft.Azure.WebJobs.Extensions.ServiceBus_5.5.1/sdk/servicebus/Microsoft.Azure.WebJobs.Extensions.ServiceBus/README.md

我认为可能有效的解决方案是将 Key Vault 添加到配置中(此处使用系统分配的托管标识):

.ConfigureAppConfiguration((_, config) =>
{
var keyVaultUrl = "...";
config.AddAzureKeyVault(new Uri(keyVaultUrl), new DefaultAzureCredential());
})

然后在属性中指定 secret 名称:

[ServiceBusTrigger(QueueName, Connection = "secret-name")] string messageJson

但这只会给我一个错误,我认为它与未正确访问服务总线有关。

System.InvalidOperationException: Can't bind parameter 'messageReceiver' to type 'Microsoft.Azure.ServiceBus.Core.MessageReceiver'

最佳答案

<小时/>

存储服务总线连接字符串,您可以使用Azure Key Vault Service

在local.settings.json中添加这行代码

"Connectionstring": "@Microsoft.KeyVault(SecretUri=https://connectionmt.vault.azure.net/secrets/AzureFunctionKeyVaultConnections/abcd46389abdeujewfuew898)"

local.settings.json 代码。

{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"ServiceBusConnectionString": "Endpoint=sb://xxxservicebusnamespace.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xxx",
"Connectionstring": "@Microsoft.KeyVault(SecretUri=https://connectionstring-mt.vault.azure.net/secrets/AzureFunctionKeyVaultConnections/xxx)"
}
}

我们创建函数,在控制台中打印连接字符串。

[FunctionName("Function1")]
public void Run([ServiceBusTrigger("myqueue", Connection = "ServiceBusConnectionString")]string myQueueItem, ILogger log)
{

string connection = Environment.GetEnvironmentVariable("Connectionstring");
Console.WriteLine(connection);
Console.ReadKey();
}

enter image description here

在此代码中,我们打印来自 Azure Key Vault 的连接字符串值。

关于c# - 使用 Microsoft.Azure.WebJobs.Extensions.ServiceBus 5.5.1 以编程方式设置连接字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73021366/

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