Post

User-secrets scratch

As a result, a new tag <UserSecretsId> user_secrets_id </UserSecretsId>
will be added to the .csproj project file and the settings file /<user_secrets_id>/secrets.json
will be created in the directory
- ~/.microsoft/usersecrets
- %APPDATA%\Microsoft\UserSecrets

  • command examples

    1
    2
    3
    4
    5
    6
    7
    8
    
      dotnet user-secrets init
      dotnet user-secrets set "Movies:ServiceApiKey" "12345"
      dotnet user-secrets set "Movies:ServiceApiKey" "12345" --project "C:\apps\WebApp1\src\WebApp1"
      cat ./input.json | dotnet user-secrets set
      dotnet user-secrets list
      dotnet user-secrets remove "Movies:ConnectionString"
      dotnet user-secrets clear
      cat ~/.microsoft/usersecrets/934ecfd0-bf73-4a27-92aa-bd6334cc944d/secrets.json
    
  • usage

1
2
3
4
5
6
7
  var configuration = new ConfigurationBuilder()
		.AddUserSecrets<Program>() 
          .Build();

	builder.AddUserSecrets(Assembly.GetExutingAssembly(),true)
	var movieApiKey = builder.Configuration["Movies:ServiceApiKey"];
	var moviesApiKey = _config["Movies:ServiceApiKey"]; //DI  IConfiguration 
  • poco settings class
1
2
3
4
  
  public class MovieSettings {
	   public string ConnectionString { get; set; }
	   public string ServiceApiKey { get; set; }
1
2
3
	var moviesConfig = 
		Configuration.GetSection("Movies").Get<MovieSettings>();
	_moviesApiKey = moviesConfig.ServiceApiKey;
1
2
3
4
5
6
	// SqlConnectionStringBuilder builder
	var conStrBuilder = new SqlConnectionStringBuilder(
			builder.Configuration.GetConnectionString("Movies"));
	conStrBuilder.Password = builder.Configuration["DbPassword"];
	var connection = conStrBuilder.ConnectionString;
This post is licensed under CC BY 4.0 by the author.