.net 具有选项模式和应用程序设置的隔离Azure函数

oxcyiej7  于 2023-10-21  发布在  .NET
关注(0)|答案(1)|浏览(117)

我想在我的隔离Azure函数中使用选项模式。我现在实现它的方式在我使用local.settings.json在本地运行它时有效,但在部署时无效。
是否可以在没有Environment.GetEnvironmentVariable(“”)的情况下执行此操作?
这是我的local.settings.json。例如,我在Azure门户中将这些设置作为应用程序设置

{
    "IsEncrypted": false,
    "Values": {
    
        "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
        "STORAGE_CONNECTION_STRING": "",
        "STORAGE_FOLDER_NAME": "",
        "STORAGE_SHARE_NAME": ""
    }
}

这是我的选修课

public class ApplicationOptions
{
    public const string Values = "Values";

    public string STORAGE_SHARE_NAME { get; set; } = string.Empty;
    public string STORAGE_FOLDER_NAME { get; set; } = string.Empty;
    public string STORAGE_CONNECTION_STRING { get; set; } = string.Empty;
}

例如在我的program.cs中

public static void Main()
    {
        var host = new HostBuilder()
            .ConfigureAppConfiguration(ConfigureAppConfiguration)
            .ConfigureServices((builder, services) =>
            {
                AddConfigurationOptions(builder, services);
            })
            .Build();

        host.Run();
    }

    private static void ConfigureAppConfiguration(HostBuilderContext hostingContext, IConfigurationBuilder config)
    {
        config.AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true);
        config.AddJsonFile("local.settings.json", true);
        config.AddEnvironmentVariables();
    }

    private static void AddConfigurationOptions(HostBuilderContext builder, IServiceCollection services)
    {
        _ = services.AddOptions<ApplicationOptions>()
            .Bind(builder.Configuration.GetSection(ApplicationOptions.Values))
            .ValidateDataAnnotations()
            .ValidateOnStart();
    }

在本地,我可以像这样访问值。

var settings = builder.Configuration
        .GetSection(ApplicationOptions.Values)
        .Get<ApplicationOptions>();

    var folderName = settings.STORAGE_FOLDER_NAME;
hts6caw3

hts6caw31#

添加到ponits @Ivan Gechev Azure => Function app => Configuration => Application settings并检查local.settings.json是否存在于相应路径中。

public static async Task<IActionResult> Run(
     [HttpTrigger(AuthorizationLevel.Function, "get", Route = "listfiles")] HttpRequest req,
     ILogger log, ExecutionContext context)
 {
     string currentDirectory = Directory.GetCurrentDirectory();
     string settingsFilePath = Path.Combine(currentDirectory, "local.settings.json");

     if (!File.Exists(settingsFilePath))
     {
         return new BadRequestObjectResult("local.settings.json not found.");
     }

     IConfigurationRoot config = new ConfigurationBuilder()
         .SetBasePath(currentDirectory)
         .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
         .AddEnvironmentVariables()
         .Build();

     string connectionString = config["AzureWebJobsStorage"];

相关问题