Azure函数应用程序:在Function App中可以不使用KeyVaultSecret C#代码吗?

pbossiut  于 2023-10-22  发布在  C#
关注(0)|答案(2)|浏览(153)

我正在开发一个函数应用程序,并试图使用密钥库来存储我的连接字符串。
在我的Web MVC应用程序中,当我们部署到生产环境时,我们不需要放入任何C#代码。
在web.config中,我们只使用这一行作为我们的连接字符串:<connectionStrings configSource="connectionStrings.config" />,它会自动拉取Azure中应用服务配置部分中的所有连接字符串。

我的主要问题:

是否可以在函数app中这样做,或者我必须直接将C#代码放入基于连接字符串名称的pull中?
下面是一个通过C#实现的示例代码。我必须根据环境切换连接字符串名称。

public async Task<string> GetConnectionStringAsync(ILogger logger)
        {
            string connectionStringName = "DefaultConnectionFunction";
            string environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            var connectionString = string.Empty;

            logger.LogInformation($"===> environment: {environment}");

            try
            {
                if (environment == "Production" || environment == "Test")
                {
                    var credential = new DefaultAzureCredential();
                    string apiUrl = Environment.GetEnvironmentVariable("KeyVaultUrl");
                    var _client = new SecretClient(new Uri(apiUrl), credential);

                    if (environment == "Test")
                    {
                        connectionStringName = $"{connectionStringName}Test";
                    }

                    KeyVaultSecret secret = await _client.GetSecretAsync(connectionStringName);
                    connectionString = secret.Value;
                }
                else if (environment == "Development")
                {
                    string jsonFile = "local.settings.json";

                    IConfigurationRoot configuration = new ConfigurationBuilder()
                            .SetBasePath(Environment.CurrentDirectory)
                            .AddJsonFile(jsonFile)
                            .Build();

                    connectionString = configuration.GetConnectionString(connectionStringName);
                }

                return connectionString;
            }
            catch (Exception ex)
            {
                // Handle exceptions here.
                throw new ApplicationException($"Unable to retrieve the secret: {connectionStringName} from Azure Key Vault", ex);
            }
        }
bfhwhh0e

bfhwhh0e1#

您是将Function App作为容器运行,还是作为.NET Function App、Linux或Windows运行?
一个选项是将连接字符串定义为Function App上的“Application Settings”,您可以将其作为环境变量读取。
此外,如果使用Azure SQL,我建议使用托管身份来避免连接字符串中的秘密。

2ic8powd

2ic8powd2#

Azure函数应用程序:在Function App中可以不使用KeyVaultSecret C#代码吗?
是的,您可以使用以下方法直接在local.settings.json中获取secret,部署后将存储在配置部分:

@Microsoft.KeyVault(VaultName=keyvaultname;SecretName=secrename)

首先创建的秘密为:

local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "con": "@Microsoft.KeyVault(VaultName=rithwik8;SecretName=connectionstring)"
  }
}

Function.cs:

using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace FunctionApp70
{
    public class Function1
    {
        private readonly ILogger _logger;
        private readonly IConfiguration config;

        public Function1(ILoggerFactory loggerFactory, IConfiguration configuration)
        {
            _logger = loggerFactory.CreateLogger<Function1>();
            config = configuration;
        }

        [Function("Function1")]
        public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
        {

            string value = config.GetValue<string>("con");
            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

            response.WriteString("Hello Rithwik The connection string is :" + value);
            return response;
        }
    }
}

Output:

相关问题