This ASP.NET blog post will show you how to create and use environment variables inside an ASP.NET application.
Environment variables are essential in managing application configurations across various development, testing, and production environments without hard-coding sensitive information.
In ASP.NET and .NET applications, utilizing environment variables improves security and flexibility. This blog post is designed to guide you through creating and effectively using environment variables in your .NET projects.
Create an Environment Variables
The first step in working with environment variables is to create them on your systems. To create an environment variables on a Windows machine. Open the PowerShell command line and run the following cmdlet.
$env:MY_VARIABLE = "MyValue"
On a Linux machine, you would use the following command.
export MY_VARIABLE="MyValue"
Once the environment variables are set, we can configure ASP.NET.
Access Environment Variables in ASP.NET
To access a defined environment variable in an ASP.NET application, we use the configuration API class to access the environment variables, as shown below.
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// Using the configuration API to access environment variables
string myVariable = Configuration["MY_VARIABLE"];
}
We use the following code to access environment variables in a .NET C# application.
using System;
public class Program
{
public static void Main()
{
string myVariable = Environment.GetEnvironmentVariable("MY_VARIABLE");
Console.WriteLine($"Environment Variable: {myVariable}");
}
}