Setting Up a Minimal API in .NET 6.0+ using Console Application

Step-by-Step Guide

Step 1: Create a Console Application

  1. Open Visual Studio.

  2. Click on "Create a new project".

  3. Choose "Console App (C#)".

  4. Description: A project for creating a command-line application that can run on .NET on Windows, Linux, macOS.

  5. Click "Next", configure your project, and create it.

Step 2: Edit .csproj File

Edit the .csproj file and change the project SDK to Microsoft.NET.Sdk.Web:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
  </PropertyGroup>

</Project>

Step 3: Add DotNetEnv Package

  1. 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

  1. Open the Program.cs file.

  2. Replace the existing code with the following to create a minimal API with a dynamic port:

Step 6: Run the API

  1. Run the API:

    • Execute the following command to run your application:

  2. 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.

Last updated