AspireDotNet

Getting started with Minimal APIs in .NET 11

Author: Areg Sarkissian

Introduction

In this post I will scaffold a .NET 11 solution called Contacts that will contain a single bare minimum Minimal Api project called Contacts.Api.

We will explore the project and solution structure, project files and how to launch and run the project.

This post uses .NET 11

Creating the project solution

Create a solution to host the project and enter the solution directory that is created:

dotnet new sln -n Contacts -o Contacts
cd Contacts

You should see a Contacts.slnx solution file in the solutions root directory.

All following dotnet cli commands are executed from the root directory of the solution.

Optionally add a .gitignore and README.md file to the solution:

dotnet new .gitignore
echo "# Contacts" >> README.md

Create the project and add to solution

Create a bare bones Minimal API project in a src subdirectory of the solution:

dotnet new web -o src/Contacts.Api

Add it to the .slnx solution file:

dotnet sln Contacts.slnx add src/Contacts.Api/Contacts.Api.csproj

The Contacts.slnx file will look like:

<Solution>
  <Folder Name="/src/">
    <Project Path="src/Contacts.Api/Contacts.Api.csproj" />
  </Folder>
</Solution>

The solution directory structure

The current solution directory structure should look like this:

.
├── .gitignore
├── Contacts.slnx
├── README.md
└── src
    └── Contacts.Api
        ├── appsettings.Development.json
        ├── appsettings.json
        ├── bin
        ├── Contacts.Api.csproj
        ├── obj
        ├── Program.cs
        └── Properties
            └── launchSettings.json

Inspecting the project file src/Contacts.Api/Contacts.Api.csproj we can see:

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

  <PropertyGroup>
    <TargetFramework>net11.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

</Project>

Inspecting the base configuration source file src/Contacts.Api/appsettings.json we can see:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Inspecting the development configuration source file src/Contacts.Api/appsettings.Development.json we can see:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  }
}

When running in development mode the appsettings.Development.json settings will override the settings in appsettings.json because in development mode the framework loads appsettings.Development.json settings after appsettings.json and overwrites any existing settings.

The appsettings.Development.json file will only be loaded by the framework when running in development mode.

The way it works is that the framework first loads appsettings.json file settings then it tries to load an appsettings.{Environment}.json templated file where {Environment} string in the template is replaced by the ASPNETCORE_ENVIRONMENT environment variable setting.

In development mode ASPNETCORE_ENVIRONMENT is set to Development so the templated file name becomes appsettings.Development.json and if that file exists, the framework will load it.

In order to only have one appsettings file as the configuration source regardless of the environment you can delete the appsettings.Development.json and only use the appsettings.json for all environments.

When running in production you can add a appsettings.Production.json file to override certain settings when running in production.

That appsettings.Production.json file will only be loaded when running in production mode where ASPNETCORE_ENVIRONMENT environment variable will be set to Production.

The Program.cs file

Inspecting the src/Contacts.Api/Program.cs file that was created by the project we can see:

Program.cs

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

This is the bare minimum code you need to run a Minimal API project and serve requests.

Here an application builder is created that we can use to add our services to the service container or configure the ASP.NET infrastructure and services before creating the application.

Then the builder is used to create the application by calling builder.Build()

The application can then be used to add middleware and endpoint handlers to the ASP.NET routing pipeline.

In this case the application maps a single endpoint handler to the GET request sent to the root application URL.

The endpoint handler is a lambda delegate closure that returns a plain text hello world! string as the response to the request.

Finally the application is run to serve requests.

Launch profiles

When we run a project using dotnet run or dotnet watch commands the application runs in an environment specified by a launch profile from the profiles in the src/Contacts.Api/Properties/launchSettings.json file.

A single profile from a list of launch profiles in the launchSettings.json file is selected for running the application.

The profiles in the launchSettings.json file specify the runtime environment and the application URL that the host server is listening on for incoming requests.

Inspecting the src/Contacts.Api/Properties/launchSettings.json file we can see:

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5242",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "https": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7044;http://localhost:5242",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

There are two profiles listed in the profiles section.

Both run in development mode as specified by the ASPNETCORE_ENVIRONMENT environment variable setting.

By default, if no profile is explicitly specified with the dotnet run or dotnet watch commands, the application runs using the first application profile in launchSettings.json.

To demonstrate using a production profile, add a third profile named http-prod that will run in production mode.

The updated file is show here:

{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5242",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "http-prod": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5242",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Production"
      }
    },
    "https": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7044;http://localhost:5242",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

As you can see we added the http-prod that has a ASPNETCORE_ENVIRONMENT setting set to Production.

When we run the application using this profile, the application will run in production mode.

Building the project

To build the project the dotnet build command must run.

The dotnet run or dotnet watch commands run the dotnet build command before running the project.

The dotnet build command runs dotnet restore command before building the project.

The dotnet restore command restores any missing nuget packages in the local package repository using the installed packages list in the project file.

When the dotnet build runs, the src/Contacts.Api/bin/Debug/net11.0/Contacts.Api.deps.json file will be updated to the full transitive dependency tree from the installed packages listed in the project file.

This file is similar to the package-lock.json file in Node.js projects.

Running the project

We can run a project using the dotnet run command.

Once tha project is running we can use the Ctrl+C key to stop running the project.

Here is the command for running the Contacts.Api project using the http profile:

dotnet run --project src/Contacts.Api/Contacts.Api.csproj --launch-profile http

The --launch-profile flag selects a run profile from the Properties/launchSettings.json file.

We can also run without specifying he launch profile

dotnet run --project src/Contacts.Api/Contacts.Api.csproj

In this case the first profile is selected by default which is the http profile.

Running the project and reloading on file changes

The dotnet watch command runs the project and then reloads the project on the fly whenever any file changes are saved.

Certain changes will not trigger the hot reload. So for that reason include the --no-hot-reload to always reload the entire project.

Running and watching the project using the http profile:

dotnet watch --no-hot-reload --project src/Contacts.Api/Contacts.Api.csproj --launch-profile http

Change Hello World! in Program.cs file to Hello World!! and save the file.

The console output will show that the change was detected and application is reloaded:

dotnet watch Exited
dotnet watch File changed: /Users/Me/Solutions/Contacts/src/Contacts.Api/Program.cs
dotnet watch Waiting for changes

Press Cmd + Shift + R to hard refresh the browser to reload the view after making file changes.

Running in Production Environment

To run using the production environment add the environment flag to override the environment setting of the http launch profile:

dotnet run --project src/Contacts.Api/Contacts.Api.csproj --launch-profile http -e ASPNETCORE_ENVIRONMENT=Production

It works with the default profile as well:

dotnet run --project src/Contacts.Api/Contacts.Api.csproj -e ASPNETCORE_ENVIRONMENT=Production

Using dotnet watch and the environment flag:

dotnet watch --no-hot-reload --project src/Contacts.Api/Contacts.Api.csproj --launch-profile http -e ASPNETCORE_ENVIRONMENT=Production

Or

dotnet watch --no-hot-reload --project src/Contacts.Api/Contacts.Api.csproj -e ASPNETCORE_ENVIRONMENT=Production

Using the production launch profile:

Another way to run in production environment is to use the production profile http-prod that we added to the Properties/launchSettings.json file.

To run in production we can simply select the http-prod profile.

dotnet run --project src/Contacts.Api/Contacts.Api.csproj --launch-profile http-prod

Or using dotnet watch:

dotnet watch --no-hot-reload --project src/Contacts.Api/Contacts.Api.csproj --launch-profile http-prod

With the production profile we don't need to use the environment flag anymore.

Conclusion

In this post we showed how to create the smallest possible Minimal API project and solution.

We then inspected and learned about all the generated files and their purpose.

Finally we built and ran the project using the dotnet run and dotnet watch commands while using different environments and launch profiles.

In following posts we will use this project and solution as a base to incrementally add more capabilities and features to our solution.