Multiple ways to organize Minimal APIs in .NET

Elevate your experience and support my work! Unlock 170+ exclusive questions and answers by becoming a Patreon

Your subscription powers the creation of valuable content. Join now for an exclusive knowledge journey!


What are Minimal APIs

Minimal APIs were introduced were introduced in .NET 6 and more light weight than controllers.

Minimal APIs are a simplified approach for building fast HTTP APIs with ASP .NET Core.

Multiple ways to organize Minimal APIs

We can organize Minimal APIs in following ways :

  • Local method

  • Extension method

  • Carter library

Local Methods

Create a local method that does not return anything in Program.cs file , add your endpoints. Multiple ways to organize Minimal APIs in .NET

Call your method before the app.Run() Multiple ways to organize Minimal APIs in .NET

Problem with this approach is as the number of APIs increases, it becomes difficult to maintain a clean and modular code structure.

Extension Method

Create an extension method for IEndpointRouteBuilder type, add all of your routes in it.

Multiple ways to organize Minimal APIs in .NET

Register it in Program.cs

Multiple ways to organize Minimal APIs in .NET

Although we have moved our code from the program file to a different file, registering new module endpoints still requires manual registration in the Program file each time.

The third approach addresses this issue by streamlining the registration process.

Carter Module

For this approach follow these three simple steps

STEP 1 - Install Package

Install Carter nuget package from nuget store.

STEP 2 - Add Configuration

Register its service and add middleware Multiple ways to organize Minimal APIs in .NET

STEP 3 - Add Routes

Now implement CarterModule and override its method AddRoutes Multiple ways to organize Minimal APIs in .NET That is all you need to do.

this way our program file stays clean and we can add as many routes as much we want by just implementing CarterModule and overriding its AddRoutes method

The responsibility of app.MapCarter is to inspect all APIs where CarterModule has been implemented and register them accordingly.

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place