Forum Discussion
iKingNinja
Nov 26, 2023Copper Contributor
Uniform way of using environment variables in development and production
Hello, i've been struggling to find an answer to this question for the past 2 days, is there a way to set environment variables in development outside of launchSettings.json and appsettings.json (to keep secrets out of version control) that will work with production env vars as well? I'd like to do this without the need to use different code for dev and production and usin:
Environment.GetEnvironmentVariable();
- alefcarlosCopper ContributorThe ASPNET Core has IConfigurarion, so this abstraction handles all the configuration provider. This is the best way to get configurations. When you create an WebApplicationBuilder this already adds the Environment Provider.
So you only need: Configuration["EnvName"].
Now, the way to set the envs depends on the distribution. If it is kubernetes, you must add to the deployment, if it is a windows service is via RegEditor.
What distribution you are using ?- DEUTSCHECLUBCopper Contributor
In ASP.NET Core, use I Configuration for handling configuration settings. When using Web Application Builder, it automatically adds the Environment Provider, simplifying access to configurations with Configuration ["E n v Name"].Vermögen
For distribution:
- In Kubernetes, add environment variables to the deployment configuration.
- For a Windows service, set environment variables via Reg Editor.
Specify your distribution for more targeted assistance.
- AddWebSolutionBrass ContributorHi @jKingNinja,
you can try this :
string connectionString = Environment.GetEnvironmentVariable("DATABASE_CONNECTION_STRING");
OR
string connectionString = Environment.GetEnvironmentVariable("DATABASE_CONNECTION_STRING")
?? Configuration.GetSection("ConnectionStrings:DefaultConnection").Value;
Here you can find the reference also,
https://learn.microsoft.com/en-us/dotnet/api/system.environment.getenvironmentvariable?view=net-8.0
Thanks & Best Regards,
AddWebSolution