dotnet-tool

using dotnet user-secrets to store a string list


how can i get to save this:

"myList" : [ "file", "something" ]

in dotnet user-secrets?

I can add this to user secrets with the command:

dotnet user-secrets set --id my-id myList "[ \"file\", \"something\" ]"

but this is saved as a string and doesnt behave the same as if read from the appsettings.json.

it appears to me that user secrets do not support json arrays. is this correct?


Solution

  • You can directly edit "user secrets" of your project. User secrets of a project are saved in "secrets.json" file. The file location is here :

    <guid> is basically GUID for your project's user secrets. you can see it in the .csproj file like this :

    <UserSecretsId>16abe888-53cb-415c-9889-797efe87c422</UserSecretsId>
    

    Here is a sample secrets.json file :

    {
    "UserSecretsConfig" : {
      "UserName1": "john.doe",
      "Password1": "pppp",
      "Domain": "company.local",
      "Uri": "https://google.com/",
      "ToEmails":["user1@example.com", "user2@example.com", "user3@example.com"]
      }
    }
    

    Here is model class for the sample user secrets :

      public class MyUserSecretsConfig
        {
            public string UserName1 { get; set; }
            public string Password1 { get; set; }
            public string Domain { get; set; }
            public string Uri { get; set; }
            public IEnumerable<string> ToEmails { get; set; }
        }
    

    Here is sample code for reading "user secrets" in a console app :

     var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddUserSecrets<Program>();
    
                var config = builder.Build();
                MyUserSecretsConfig mySecrets = config.GetSection("UserSecretsConfig")
                          .Get<MyUserSecretsConfig>();
    

    In order the above shown code to work you have to add these packages to your project:

    In addition, if you will be accessing user secrets in a ASP.NET Core application the Configuration is available via Injection at Startup class. There is no need for ConfigurationBuilder.

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }