Environment variables are a powerful way to configure settings in ASP.NET Core applications, especially for sensitive information such as connection strings, API keys, and other configuration settings that should not be hard-coded in the application. This approach enhances security and allows for easy configuration changes without modifying the code.

Key Concepts of Environment Variables

  • Separation of Concerns: Environment variables allow you to separate configuration from code, making it easier to manage different settings for development, testing, and production environments.
  • Security: Storing sensitive information in environment variables helps prevent accidental exposure in source control.
  • Flexibility: You can easily change environment variables without redeploying the application, making it suitable for cloud-based deployments.

Setting Environment Variables

Environment variables can be set in various ways, depending on the operating system and the hosting environment. Below are examples for different platforms:

Windows

        
setx MyAppSetting "SomeValue"

Linux/macOS

        
export MyAppSetting="SomeValue"

Docker

        
docker run -e MyAppSetting="SomeValue" myapp

Accessing Environment Variables in ASP.NET Core

In an ASP.NET Core application, you can access environment variables using the IConfiguration interface. The configuration system automatically includes environment variables, making them available for use throughout the application.

Sample Code

        
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

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

public IConfiguration Configuration { get; }

public void ConfigureServices(IServiceCollection services)
{
// Accessing an environment variable
var myAppSetting = Configuration["MyAppSetting"];
services.AddSingleton(new MyService(myAppSetting));
services.AddControllersWithViews();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

public class MyService
{
private readonly string _setting;

public MyService(string setting)
{
_setting = setting;
}

public string GetSetting()
{
return _setting;
}
}

Explanation of the Sample Code

In the sample code above:

  • Constructor Injection: The Startup class constructor receives an IConfiguration instance, which is used to access configuration settings, including environment variables.
  • Accessing the Environment Variable: The line var myAppSetting = Configuration["MyAppSetting"]; retrieves the value of the environment variable MyAppSetting.
  • Service Registration: The retrieved value is passed to a service class MyService, which can use it as needed.

Using Environment Variables in Different Environments

ASP.NET Core applications can be configured to use different environment variables based on the environment they are running in (Development, Staging, Production). You can set the ASPNETCORE_ENVIRONMENT variable to specify the environment:

        
setx ASPNETCORE_ENVIRONMENT "Development"

You can then create environment-specific configuration files (e.g., appsettings.Development.json</code >) that can also reference these environment variables, allowing for a more tailored configuration based on the environment.
</p>

<h2>Conclusion</h2>
<p>
Using environment variables in ASP.NET Core applications is a best practice for managing configuration settings, especially sensitive information. By leveraging the <code>IConfiguration
interface, developers can easily access these variables, ensuring that applications remain secure and flexible across different environments. This approach not only enhances security but also simplifies the deployment process, making it easier to manage configurations in cloud-based and containerized environments.