在函数体内访问存储帐户连接字符串

问题描述

我有一个队列触发器(例如):

        [FunctionName("Handle-Invoice")]
        [StorageAccount("StorageAccountConnectionString")]
        public async Task InvoiceQueueTrigger(
            [QueueTrigger("invoice-queue")] CloudQueueMessage cloudMessage,ExecutionContext context,ILogger log)
        {
            // Async code which might need access to the storage account for the queue
        }

其中 StorageAccountConnectionString函数的配置中定义。

我想知道是否有办法隐式访问 StorageAccount 属性中定义的连接字符串的值?

我知道我可以直接从环境或配置访问该值,但最好通过绑定或其他方法访问该值。

谢谢。

解决方法

connection string 的格式是这样的:

DefaultEndpointsProtocol=[http|https];AccountName=myAccountName;AccountKey=myAccountKey

您可以使用以下代码生成连接字符串:

            var accountName = "<your-account-name>";
            var keyValue = "<your-storage-key>";
            var useHttps = true;
            var connValid = true;

            var storageCredentials = new StorageCredentials(accountName,keyValue);
            var storageAccount = new CloudStorageAccount(storageCredentials,useHttps);
            var connString = storageAccount.ToString(connValid);

            CloudStorageAccount sa = CloudStorageAccount.Parse(connString);

但是你需要明确地使用你的storage account key来生成你的connection string,如果你不想使用storage account key,我认为很难生成你的{{1} }.

如果您担心显式使用 connection String 的风险,您可以使用 key vault 来保护它。这样,您就可以安全地configure the key vault reference in the Azure function configuration file

注意:

据我所知,connection string不能在本地使用,需要在key vault中测试。