Environment Variables and Secrets in .NET Core: Best Practices
- Published on
- • 1 mins read•--- views
Environment - is exactly the place, where you gonna be store such variables as connections string, different usernames for authorisations in external systems, ports, number settings and etc.
Dotnet framework provides special interface for working with env files and, also, special secured container for more sensible and secured information called user-secrets
.
Adding secrets to project
dotnet user-secrets init
dotnet user-secrets set "Redis:ConnectionString" "12345"
Accessing configuration (for secrets - similar)
IConfiguration configuration;
// with get
Configuration.GetSection("Redis")
// indexed key style
Configuration["Redis:ConnectionString"]
Mapping configuration to POCO
var moviesConfig = Configuration.GetSection("Redis").Get<RedisOptions>();
Accessing configuration object through Dependency Injection
class RedisOptions {
public string ConnectionString {get; set;}
//...
}
// binding configuration section to runtime object
services.Configure<RedisOptions>("Redis");
// Accessing anywhere in constructor through DependencyInjection
class Controller {
public Controller(IOptions<JwtSettingsDto> jwtOptions)
{
//...
}
}
Accessing connection string
Configuration.GetConnectionString("DefaultConnectionString");