Search code examples
c#.net.net-6.0

the configuration file 'secrets.json' was not found and is not optional (.NET 6)


User Secrets error is being generated in a CI/CD pipeline, when secrets.json file shouldn't be expected.

Steps:

  1. Create .NET 5 project
  2. Added user secrets.
  3. Code runs locally and in CI/CD pipelines.
  4. Upgrade to .NET 6 project (and preview NuGet 6.* packages)

Code runs locally, but fails in CI/CD pipelines, with error:

"The configuration file 'secrets.json' was not found and is not optional."

Expected:

Code runs without the secrets.json file being present Configuration .NET 6, Microsoft.Extensions.Configuration.UserSecrets: 6.0.0-preview.1.21102.12

Regression? This works in .NET 5, Microsoft.Extensions.Configuration.UserSecrets: 5.0.0.*

System.IO.FileNotFoundException: The configuration file 'secrets.json' was not found and is not optional. The physical path is '/home/runner/work/UserSecretsRegression/UserSecretsRegression/UserSecrets/UserSecrets.Tests/bin/Release/net6.0/secrets.json'.
  Stack Trace:
      at Microsoft.Extensions.Configuration.FileConfigurationProvider.HandleException(ExceptionDispatchInfo info)
   at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load(Boolean reload)
   at Microsoft.Extensions.Configuration.FileConfigurationProvider.Load()
   at Microsoft.Extensions.Configuration.ConfigurationRoot..ctor(IList`1 providers)
   at Microsoft.Extensions.Configuration.ConfigurationBuilder.Build()
   at UserSecrets.Tests.UnitTest1.TestMethod1() in /home/runner/work/UserSecretsRegression/UserSecretsRegression/UserSecrets/UserSecrets.Tests/UnitTest1.cs:line 13

Solution

  • https://github.com/dotnet/runtime/issues/48485

    Basically, it's a new feature in .NET6 that 'secrets.json' is not optional by default!

    AddUserSecrets(this IConfigurationBuilder configuration, Assembly assembly, bool optional);
    

    That 'optional' parameter should be set to 'true' in your code.

     var configuration = new ConfigurationBuilder()
        .AddEnvironmentVariables()
        .AddCommandLine(args)
        .AddJsonFile("appsettings.json")
        .AddUserSecrets<Program>(true)
        .Build();