从 Azure Functions 中的配置文件加载连接字符串

Load Connection String from Config File in Azure Functions

在我的 Azure 函数中,我使用了一个库,它通过来自 ConfigurationManager 的 ConnectionString 建立与 SQL 服务器的连接,如下所示:

var cs = System.Configuration.ConfigurationManager.ConnectionStrings["DbConString"].ConnectionString;
DbConnection connection = new SqlConnection(cs);

现在,当我通过应用程序设置在门户中设置连接字符串 DbConString 时,一切正常。但是对于本地开发,我使用 azure-functions-cli,不幸的是,我不知道应该将连接字符串放在哪里,以便通过 ConfigurationManager 正确加载它。

我试图将其放入 appsettings.json 文件,但没有成功。

编辑: 我的 appsettings.json 目前看起来像这样:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsDashboard": "",
    "MyServiceBusReader": "Endpoint=sb://xxxx=",
    "DbConStr1": "data source=(localdb)\MSSQLLocalDB;initial catalog=MyDb;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework",
    "ConnectionStrings": {
      "DbConStr2": "data source=(localdb)\MS..." 
    } 
  }
}

但我无法通过 ConfigurationManager 访问 "DbConStr1"。 如 here 所述,在 "ConnectionStrings" 中添加 "DbConStr2" 会导致编译错误。可能是因为我没有使用 .NET Core?

编辑2: 我搞砸了 "ConnectionStrings" 的嵌套。它必须在与 "Values":

相同的嵌套级别
{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsDashboard": "",
    "MyServiceBusReader": "Endpoint=sb://xxxx="
  },
  "ConnectionStrings": {
    "DbConStr": "data source=(localdb)\MS..." 
  }
}

您应该能够使用项目结构中的 appsettings.json 文件来管理您的配置设置。您可以查看 here Azure Functions 的文件夹结构示例。

此外,this link 将详细介绍如何使用 .NET Core 管理配置设置。

问题是,例如从Web.config 文件由两部分组成:

  • 连接字符串本身和
  • 提供商名称。

但由于配置文件使用 JSON 格式,因此无法同时指定这两个参数。

在提出问题时,无法在 appsetings.json 中设置提供商名称(现已重命名为 local.settings.json)。但是 Azure-Functions-team 改变了这一点并将 providerName 的默认值设置为 System.Data.SqlClient,这解决了问题。

providerName默认为System.Data.SqlClient。您不必手动设置它。只需添加您的连接字符串 X 并通过 ConfigurationManager.ConnectionStrings["X"].

读取它

我遇到了同样的问题并且正在使用 .net 标准(而不是核心)。我将我的设置添加到我的 Azure 函数的“应用程序设置”部分(在 Azure 门户中):-

然后我下载了函数的 zip:-

此下载中包含 local.settings.json 的副本,其中包含我的应用程序设置,格式正确 json。然后我通过 ConfigurationManager.Appsettings["mysetting"]

访问它们

添加文件local.setting.json

  {
    {
      "IsEncrypted": false,
       "Values": {
      "AzureWebJobsStorage": "UseDevelopmentStorage=true",
      "AzureWebJobsDashboard": "UseDevelopmentStorage=true",

      "tenantId": "You tenantId",
      "resource": "https://management.azure.com/",
      "ClientSecret": "You ClientSecret, Key from App Registry",
      "ClientId": "You ClientId, Application ID from App registry",

      "subscriptionId": "You subscriptionId",
      "resourceGroupName": "Your resourceGroupName",
      "serverName": " Your SQL Server",
      "databaseNameDW": "Your Database",
      "apiversion": "2017-10-01-preview"      
    }
}

在 C# 代码中使用:

private readonly static string tenantId = ConfigurationManager.AppSettings["tenantId"];
// C# Environment Variables example for Azure Functions v1 or v2 runtime
// This works all the way up to but not including .NET Core 2.0
var clientId = Environment.GetEnvironmentVariable("ClientId");
var clientSecret = Environment.GetEnvironmentVariable("ClientSecret");
var aadDomain = Environment.GetEnvironmentVariable("AADDomain");

请记住,您在 local.settings.json 中所做的设置不会反映在 azure 中。请按照 link- 从 Azure 门户在应用程序设置中添加您的值 https://docs.microsoft.com/en-us/azure/azure-functions/functions-how-to-use-azure-function-app-settings

我发现了一种方法,感觉 很笨拙,但有效:如果你评估 Environment.GetEnvironmentVariables(),你可以从你的 [=18= 中发现所有连接字符串] 在本地 运行 时可作为带有 "ConnectionStrings:" 前缀的环境变量使用,如果在 Azure 上 运行 则可作为多个 "xxxCONNSTR_" 中的一个,因此您可以定义此辅助函数:

    private static Array ConnectionStringKeyPrefixes = new[] { "ConnectionStrings:", "SQLCONNSTR_", "SQLAZURECONNSTR_", "MYSQLCONNSTR_", "POSTGRESQLCONNSTR_", "CUSTOMCONNSTR_" };
    public static string GetConnectionStringFromSettings(string connectionStringName)
    {
        string connectionString = null;

        foreach(string prefix in ConnectionStringKeyPrefixes) {
            connectionString = Environment.GetEnvironmentVariable($"{prefix}{connectionStringName}");

            if (!string.IsNullOrWhiteSpace(connectionString))
            {
                break;
            }
        }

        return connectionString;
    }