Search code examples
c#asp.net-coredocker-secrets

KeyPerFileConfigurationSource doesn't have an option to set directory path and ignore condition at the same time


I am using .NET Core 3.1 and Docker secrets to store sensitive configuration data. I am using AddKeyPerFile extension method to tell .NET Core to load key-value pairs from files on file system. I want to set directoryPath where these files are located and IgnoreCondition to ignore specific files. However, KeyPerFileConfigurationBuilderExtensions only contains the following two methods:

public static IConfigurationBuilder AddKeyPerFile(this IConfigurationBuilder builder, Action<KeyPerFileConfigurationSource> configureSource);
public static IConfigurationBuilder AddKeyPerFile(this IConfigurationBuilder builder, string directoryPath, bool optional);

... and KeyPerFileConfigurationSource contains the following properties:

public IFileProvider FileProvider { get; set; }
public Func<string, bool> IgnoreCondition { get; set; }
public string IgnorePrefix { get; set; }
public bool Optional { get; set; }

This is the code that I have currently:

ConfigurationBuilder cb = new ConfigurationBuilder();
// I want to set 'IgnoreCondition' as well
cb.AddKeyPerFile(directoryPath: "/abc123", optional: true);

How can I set both directoryPath AND IgnoreCondition?


Solution

  • I found a solution. You should use PhysicalFileProvider like so:

    ConfigurationBuilder cb = new ConfigurationBuilder()
        .AddKeyPerFile(x =>
        {
            x.FileProvider = new PhysicalFileProvider("/abc123");
            x.Optional = true;
            x.IgnoreCondition = fileName => !fileName.StartsWith("MyApp_");
        });