0

我在 Azure 函数中有 app.config 文件,我想在运行时读取 appsettings。我更新了 csproj 文件以添加要删除的 app.config 文件在 'bin\Debug\netcoreapp3.1' 以及 bin\Debug\netcoreapp3.1\bin

但是在读取 appsettings 值时我得到了空值。另外,我尝试了 System.Configuration.ConfigurationManager 的 5.0 和 6.0 版,但没有运气。

我需要帮助解决这个问题。我想访问 app.config 文件运行时。不知道我错过了什么

Azure 功能是否支持访问 app.config 文件?我不想在函数应用程序或 local.settings 中使用应用程序设置,因为我有太多字符串

4

1 回答 1

0

在 Azure Function Runtime 版本 V1 的情况下,为了更早地访问应用程序设置,我们使用了ConfigurationManager。但是在最新版本的 Azure Function 上,我们改用ConfigurationBuilder

我们还可以使用System.Environment.GetEnvironmentVariable来读取应用程序设置或应用程序设置。

以下是配置生成器的语法

var value = Environment.GetEnvironmentVariable("Put the key value");

对于本地开发,您可以将自定义设置添加到 local.settings.json 文件,但如果您部署到 Azure,则此设置仅对本地开发有用,您将不会获得该参考。

{
    "IsEncrypted": false,
    "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "custom key": "custom value"

  }
}

在这种情况下,您的函数可能如下所示

using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Extensions.Configuration;

namespace FunctionApp5
{
    public static class MyNewHTTPFunction
    {
        [FunctionName("MyNewHTTPFunction
")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            log.LogInformation("MyProductHTTPFunction function processed a request.");

            var newconfiguration = new ConfigurationBuilder()
    .SetBasePath(context.FunctionAppDirectory)
    .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
    .AddEnvironmentVariables()
    .Build();
var appSettingsVal = newconfiguration["appSettingKey"];
var myconnection = newconfiguration.GetConnectionString("YourSqlConnectionString");

检查ConfigurationBuilder以获取更多详细信息。

于 2021-08-19T10:38:15.177 回答