You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Azure Function中创建并使用app.config,通过ConfigurationManager读取配置

Hey there, let's walk through both of these scenarios clearly—they're super common when working with .NET apps and Azure Functions, so I'll break them down step by step with code examples.

1. 在Azure Function中使用app.config并通过ConfigurationManager读取配置

Azure Functions default to using local.settings.json for local development and Azure Portal app settings for deployment, but if you need to use app.config (for example, to reuse existing .NET Framework code), here's how to set it up:

Step 1: Install the required NuGet package

First, you need the System.Configuration.ConfigurationManager package, since it's not included by default in Azure Function projects. Install it via:

  • Package Manager Console:
    Install-Package System.Configuration.ConfigurationManager
    
  • .NET CLI:
    dotnet add package System.Configuration.ConfigurationManager
    

Step 2: Create and configure your app.config file

Right-click your Azure Function project → Add → New Item → Select "Application Configuration File" (name it app.config), then add your settings inside the <appSettings> or <connectionStrings> nodes:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="ExternalApiUrl" value="https://api.example.com/v1" />
    <add key="MaxRetryCount" value="3" />
  </appSettings>
  <connectionStrings>
    <add name="MyDbConnection" connectionString="Server=myDbServer;Database=myDb;User Id=myUser;Password=myPass;" />
  </connectionStrings>
</configuration>

Step 3: Set copy-to-output properties

Right-click the app.config file → Properties → Set "Copy to Output Directory" to Copy if newer or Copy always. This ensures the file is included in your deployment package.

Step 4: Read settings with ConfigurationManager

Now you can access the settings in your function code like this:

using System.Configuration;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;

namespace MyAzureFunction
{
    public static class ConfigReaderFunction
    {
        [FunctionName("ConfigReaderFunction")]
        public static void Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger log)
        {
            // Read appSettings
            string apiUrl = ConfigurationManager.AppSettings["ExternalApiUrl"];
            int maxRetries = int.Parse(ConfigurationManager.AppSettings["MaxRetryCount"]);
            
            // Read connection strings
            string dbConnString = ConfigurationManager.ConnectionStrings["MyDbConnection"].ConnectionString;

            log.LogInformation($"External API URL: {apiUrl}");
            log.LogInformation($"Max retry count: {maxRetries}");
            log.LogInformation($"DB Connection String: {dbConnString}");
        }
    }
}

Important note for Azure deployment

When deploying to Azure, app.config settings won't automatically sync to Azure's app settings. You have two options:

  • Manually add all app.config key-value pairs to your Function App's Configuration → Application Settings in the Azure Portal (this is the recommended approach for security and environment-specific configurations).
  • Ensure the app.config file is included in your deployment package (but be cautious with sensitive data like connection strings here).
2. 创建app.config文件并借助ConfigurationManager.AppSettings读取配置(通用.NET项目)

This applies to traditional .NET Framework projects, or .NET Core/.NET 5+ projects where you need to use the legacy ConfigurationManager approach:

Step 1: Add the app.config file

Right-click your project → Add → New Item → Select "Application Configuration File" (keep the default name app.config), then click Add.

Step 2: Populate your settings

Edit the app.config file to add your desired settings in the <appSettings> section:

<configuration>
  <appSettings>
    <add key="AppName" value="My .NET App" />
    <add key="DefaultTimeout" value="30000" />
    <add key="ApiSecret" value="mySuperSecretValue123" />
  </appSettings>
</configuration>

Step 3: Install the ConfigurationManager package (if needed)

  • For .NET Framework projects: This package is usually included by default, but if you get errors, install it via the commands in Step 1 of the Azure Function section.
  • For .NET Core/.NET 5+ projects: You must install the System.Configuration.ConfigurationManager NuGet package (same commands as before).

Step 4: Read settings in your code

Here's an example for a console app:

using System;
using System.Configuration;

namespace MyDotNetApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string appName = ConfigurationManager.AppSettings["AppName"];
            int timeout = int.Parse(ConfigurationManager.AppSettings["DefaultTimeout"]);
            string apiSecret = ConfigurationManager.AppSettings["ApiSecret"];

            Console.WriteLine($"App Name: {appName}");
            Console.WriteLine($"Default Timeout (ms): {timeout}");
            Console.WriteLine($"API Secret: {apiSecret}");
        }
    }
}

Quick tip

For connection strings, use the <connectionStrings> node instead of <appSettings>, and read them with ConfigurationManager.ConnectionStrings["YourConnName"].ConnectionString—this is the standard practice for database connections in .NET.


内容的提问来源于stack exchange,提问作者demalegabi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:48:39