UserSecretsIdAttribute attribute = assembly.GetCustomAttribute<UserSecretsIdAttribute>();
if (attribute != null)
{
- return AddUserSecrets(configuration, attribute.UserSecretsId, reloadOnChange);
+ return AddUserSecretsInternal(configuration, attribute.UserSecretsId, optional, reloadOnChange);
}
if (!optional)
/// <param name="reloadOnChange">Whether the configuration should be reloaded if the file changes.</param>
/// <returns>The configuration builder.</returns>
public static IConfigurationBuilder AddUserSecrets(this IConfigurationBuilder configuration, string userSecretsId, bool reloadOnChange)
+ => AddUserSecretsInternal(configuration, userSecretsId, true, reloadOnChange);
+
+ private static IConfigurationBuilder AddUserSecretsInternal(IConfigurationBuilder configuration, string userSecretsId, bool optional, bool reloadOnChange)
{
if (configuration == null)
{
throw new ArgumentNullException(nameof(userSecretsId));
}
- return AddSecretsFile(configuration, PathHelper.GetSecretsPathFromSecretsId(userSecretsId), reloadOnChange);
+ return AddSecretsFile(configuration, PathHelper.GetSecretsPathFromSecretsId(userSecretsId), optional, reloadOnChange);
}
- private static IConfigurationBuilder AddSecretsFile(IConfigurationBuilder configuration, string secretPath, bool reloadOnChange)
+ private static IConfigurationBuilder AddSecretsFile(IConfigurationBuilder configuration, string secretPath, bool optional, bool reloadOnChange)
{
string directoryPath = Path.GetDirectoryName(secretPath);
PhysicalFileProvider fileProvider = Directory.Exists(directoryPath)
? new PhysicalFileProvider(directoryPath)
: null;
- return configuration.AddJsonFile(fileProvider, PathHelper.SecretsFileName, optional: true, reloadOnChange);
+ return configuration.AddJsonFile(fileProvider, PathHelper.SecretsFileName, optional, reloadOnChange);
}
}
}
}
[Fact]
+ public void AddUserSecrets_DoesThrowsIfNotOptionalAndSecretDoesNotExist()
+ {
+ var secretId = Assembly.GetExecutingAssembly().GetName().Name;
+ var secretPath = PathHelper.GetSecretsPathFromSecretsId(secretId);
+ if (File.Exists(secretPath))
+ {
+ File.Delete(secretPath);
+ }
+
+ Assert.Throws<FileNotFoundException>(() => new ConfigurationBuilder().AddUserSecrets(Assembly.GetExecutingAssembly(), false).Build());
+ }
+
+ [Fact]
[ActiveIssue("https://github.com/dotnet/runtime/issues/34580", TestPlatforms.Windows, TargetFrameworkMonikers.Netcoreapp, TestRuntimes.Mono)]
public void AddUserSecrets_With_SecretsId_Passed_Explicitly()
{