【问题标题】:Load Connection String from Config File in Azure Functions从 Azure Functions 中的配置文件加载连接字符串
【发布时间】:2025-12-26 08:25:11
【问题描述】:

在我的 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”的嵌套。它必须与“值”处于同一嵌套级别:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "AzureWebJobsDashboard": "",
    "MyServiceBusReader": "Endpoint=sb://xxxx="
  },
  "ConnectionStrings": {
    "DbConStr": "data source=(localdb)\\MS..." 
  }
}

【问题讨论】:

  • 您使用的是 .NET Core 吗?我假设您使用的是application.json 文件。
  • 不,我不使用 .NET Core。我认为使用 application.json 就是 Azure Functions 的工作原理?
  • 实际上,至少在我看来,启动 .NET 函数使用 v4.6,所以您是正确的,因为它还不是 .NET Core。
  • 这是否意味着也应该可以使用 app.config 而不是 application.json?
  • 根据您的编辑,您的连接字符串绝对应该在ConnectionStrings 节点下。您可以访问任何设置吗?我可能会尝试确保文件被正确命名为appsettings.json,以防您的函数配置为按约定查找该文件名。

标签: c# azure azure-functions


【解决方案1】:

问题是,从例如已知的连接字符串Web.config 文件由两部分组成:

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

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

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

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

【讨论】:

  • 你能提供一些代码或链接来告诉我们这是如何实现的吗?
  • 是如何实现的? providerName 默认为 System.Data.SqlClient。您不必手动设置它。只需添加您的连接字符串 X 并通过 ConfigurationManager.ConnectionStrings["X"] 读取它
  • ConfigurationManager 来自哪个命名空间?
【解决方案2】:
// 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 中。请按照以下链接在 Azure 门户的应用设置中添加您的值 - https://docs.microsoft.com/en-us/azure/azure-functions/functions-how-to-use-azure-function-app-settings

【讨论】:

    【解决方案3】:

    我找到了一个感觉很老套但有效的方法:如果你评估Environment.GetEnvironmentVariables(),你会发现local.settings.json中的所有连接字符串都可以作为环境变量使用"ConnectionStrings:" 前缀,如果在本地运行,或者从多个 "xxxCONNSTR_" 中的一个,如果在 Azure 上运行,那么您可以定义这个辅助函数:

        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;
        }
    

    【讨论】:

      【解决方案4】:

      添加文件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"];
      

      【讨论】:

      • 如何推送 local.setting.json ?我已经从 github repo 部署了我的 azure 函数,所以我要在我的 repo 中添加这个文件。
      • 在天蓝色函数 v2 中,ConfigurationManager.AppSettings 不会从 local.settings.json 文件中加载任何内容!
      【解决方案5】:

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

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

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

      【讨论】:

        【解决方案6】:

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

        此外,this 链接将包含有关如何使用 .NET Core 管理配置设置的一些详细信息。

        【讨论】: