Will discuss the difference between .NET 9 Core Minimal API Controller APIs. Minimal API is a fast and lightweight API development introduced in .NET 6.0, and it is enhanced in .NET 9. Also, well-suited for lightweight services, microservices, and small APIs. Routing and [HttpGet] attributes are not there in the minimal API. More simple and Program.cs, all the logics are defined. The controller-based API is MVC (Model-View-Controller) pattern-based, also structured, and scalable. It will be suitable for large and complex applications. Logics are organized in separate controller classes.
Minimal API (.NET 9) |
Controller API (.NET 9) |
Quick APIs, small and compact for micro services |
Complex APIs, larger, and enterprise apps |
Lambda expressions are used and in-line based logic development |
Routing is based on the Attribute and Controller APIs |
Dependency Injection is supported |
Dependency Injection is supported and more structured |
Less structured for Testing & Maintainability can be handled for larger apps also |
Unit Testing & Maintainability is easier with the separation of concerns |
Complex routing or filter options are limited |
Complex routing or filters are supported and structured |
Will see how to create and run both a minimal API and a Controller API. First, to create the minimal API, run the following command in the command line.
dotnet new web -n MinimalApiDemo
cd MinimalApiDemo
In the program.cs file mapping the URL and function, there are no controllers and attributes; simply added routed mappings.
Minimal API Example
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var products = new List<Product>
{
new(1, "Laptop", 999.99m),
new(2, "Phone", 499.99m)
};
app.MapGet("/products", () => products);
app.MapGet("/products/{id}", (int id) =>
products.FirstOrDefault(p => p.Id == id) is Product product
? Results.Ok(product)
: Results.NotFound());
app.MapPost("/products", (Product product) =>
{
products.Add(product);
return Results.Created($"/products/{product.Id}", product);
});
app.Run();
To check the output, visit 'https://localhost:5001/product/1'.
Controller API Example
To create an MVC controller-based AP,I run the below command.
dotnet new webapi -n ControllerApiDemo
cd ControllerApiDemo
Here we will have a simple product API example, with [HttpGet] routing example given below.
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
private static readonly List<Product> Products = new()
{
new Product { Id = 1, Name = "Laptop", Price = 1200 },
new Product { Id = 2, Name = "Smartphone", Price = 800 }
};
[HttpGet]
public ActionResult<IEnumerable<Product>> GetAll()
{
return Ok(Products);
}
[HttpGet("{id}")]
public ActionResult<Product> GetById(int id)
{
var product = Products.FirstOrDefault(p => p.Id == id);
if (product == null) return NotFound();
return Ok(product);
}
}
To check the output, visit 'https://localhost:5001/api/products'