Install the DotNetEnv package by running the following command in the terminal:
Step 4: Create a .env File
Create a .env file in the root of your project directory and add your environment variables. For example:
Step 5: Create an Example API
Open the Program.cs file.
Replace the existing code with the following to create a minimal API with a dynamic port:
Step 6: Run the API
Run the API:
Execute the following command to run your application:
Test the API:
Open your browser or a tool like Postman.
Navigate to http://localhost:<port>/api/example to see the response from the HttpGet endpoint. Replace <port> with the port number specified in your .env file.
Summary
This guide covers setting up a minimal API using a .NET 6.0+ console application. It includes steps for creating the project, configuring it to use the Microsoft.NET.Sdk.Web SDK, adding the DotNetEnv package for environment variable management, and implementing a simple HttpGet endpoint. Additionally, it details how to dynamically set the port number using a .env file, providing flexibility for different deployment environments. By following these steps, you can quickly set up and test a minimal API with a dynamic port configuration.
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using DotNetEnv;
// Load environment variables from .env file
Env.Load();
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Map the example GET endpoint
app.MapGet("/api/example", () => "Hello, World!");
// Get the port number from environment variable or use a default
var port = Environment.GetEnvironmentVariable("PORT") ?? "5000";
// Start the application on the specified port
app.Urls.Add($"http://*:{port}");
app.Run();