Home > Enterprise >  Steps needed to have a .NET Console Application read secrets.json in Visual Studio
Steps needed to have a .NET Console Application read secrets.json in Visual Studio

Time:10-18

I'm following the docs for Configuration in .Net, and having trouble getting it working with User Secrets in Visual Studio 2022 (.Net 6.0).

Thus far I've:

  1. Installed Microsoft.Extensions.Configuration.UserSecrets, and Microsoft.Extensions.Hosting.
  2. Confirmed that <UserSecretsId> was added to the .csproj file

Code

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

// Retrieve App Secrets
using IHost host = Host.CreateDefaultBuilder(args).Build();
IConfiguration config = host.Services.GetRequiredService<IConfiguration>();

string secret = config.GetValue<string>("DUMMY_VALUE");

...

await host.RunAsync();

secrets.json (Opened by right-clicking the project and choosing 'Manage User Secrets')

{
   "DUMMY_VALUE": "dummy-test-value"
}

In the above, secret is null. Based on this line from the docs, I thought the code above would create a default config capable of reading the secrets.json file.

It seems like the way this works has been updated since similar questions were asked and answered, like this one. I've also been referencing the docs on Secrets in ASP applications, but still having trouble spotting what I'm missing.

CodePudding user response:

With help from this answer and the docs for AddUserSecrets, I have a working solution: construct a custom config object with the desired capability.

code

using Microsoft.Extensions.Configuration;

// Retrieve App Secrets
IConfiguration config = new ConfigurationBuilder()
    .AddUserSecrets<SomeClass>()
    .Build();

string secret = config.GetValue<string>("DUMMY_VALUE");

...

Here, SomeClass can be any class in the assembly. The in-IDE description for AddUserSecrets<T> says:

AddUserSecrets will search the assembly that contains class T for some instance of Microsoft.Configuration.UserSecrets.UserSecretsIdAttribute which specifies the user secrets ID.

After following the steps listed in the question, this code succeeds in reading the secrets.json file. This solution is hinted at in the docs on Secrets in ASP.NET Core applications.

As mentioned by Bellrampion, the steps described in the Configuration in .Net docs will only read the secrets.json file in the Development configuration - which I do not see as an option in Visual Studio 2022. Based on this, if you want to use User Secret management in a .Net Console application in VS 2022, you may need to construct the custom config object like above.

  • Related