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!
About today’s newsletter :
In today’s newsletter we are going to discuss:
What are Minimal APIs
Ways to organize them
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 :
1/ Local method
2/ Extension method
3/ Carter library
Local Methods
Create a local method that does not return anything in Program.cs
file , add your endpoints.
Call your method before the app.Run()
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.
Register it in Program.cs
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
SEP 1 - Install Package
Install Carter nuget package from nuget store.
STEP 2 - Add Configuration
Register its service and add middleware
STEP 3 - Add Routes
Now implement CarterModule
and override its method AddRoutes
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.
Whenever you’re ready, there is 1 way I can help you
Promote yourself to 7500+ subscribers by Sponsoring my Newsletter
Special Offer
Pragmatic Clean Architecture: Learn how to confidently ship well-architected production-ready apps using clean architecture. [ 10% discount with promo code MUWAS]
Making learning easier for .NET community, please check out this repository to find out list of Youtubers, Bloggers and Coures (paid/free) for .NET
If I add new endpoints in existing extension methods I don't need to modify program.cs file right?. I agree it would break OCP but still if its less endpoints would it not be better than carter module?
After adding Carter it throwed the 'Unable to configure HTTPS endpoint. No server certificate was specified, and the default developer certificate could not be found or is out of date. To generate a developer certificate run 'dotnet dev-certs https'.
after running the command and API its start showing as unsafe website
do i need to change any thing more