DotNetEnv

A .env file is a simple text file used to store environment variables, which are key-value pairs used by your application during runtime. Environment variables can store configuration settings, sensitive information like API keys, database connection strings, and other data that you do not want to hardcode in your application's source code.

  1. Security: Keeps sensitive information like API keys and passwords out of your source code.

  2. Configuration: Makes it easy to change configuration settings without modifying your code.

  3. Portability: Simplifies the process of moving an application between different environments (development, testing, production) with different configurations.

  4. Convenience: Centralizes configuration in one place, making it easier to manage and update.


  1. Create a .env File: Add your environment variables in a .env file located at the root of your project.

  2. Load the .env File: Use a package like DotNetEnv to load the variables into your application.

  3. Access the Variables: Retrieve the variables from the environment in your code.

Example with ASP.NET Core Web API

Here’s how you can use a .env file in an ASP.NET Core Web API project using top-level statements:

1. Install the DotNetEnv Package

Open your terminal and install the DotNetEnv package:

dotnet add package DotNetEnv

2. Create a .env File

Create a .env file in the root directory of your project and add your environment variables:

ConnectionStrings__DBCon=YourSecureConnectionString
API_KEY=YourAPIKey

3. Update Program.cs with Top-Level Statements

Modify your Program.cs file to load the environment variables and configure the services:

Program.cs

4. Add Database Context

If you’re using Entity Framework Core, add the ApplicationDbContext:

ApplicationDbContext.cs

Last updated