In this article, we are going to learn about Minimal API that was a new feature released in .Net Core 6.0.
What is Minimal API?
Minimal means that it contains the essential components needed to build HTTP APIs. Basically, with minimal API, all you need is a program.cs to get started.
It is an approach to building APIs without all the complex structures of MVC.
Benefits of Minimal API
- Reduce complexity.
- Easy to start: all you need is the Program.cs and your csproj and a few line of code to create your first API.
- It’s powered by .Net 6 and C# 10 so all of the latest improvements and functionalities are supported out of the box
API without controllers. - Performance: The application is simplified which means that the application runs much faster and is easy to build and compile.
Prerequisites
Let us understand with the help of an example.
First, open Visual Studio 2022 and create a .NET 6.0 application by clicking Create a new project.
Choose ASP.NET Core Web API.
Now, set the Project Name and Location, and then click on the Next button.
Now, set the Target Framework as .NET 6.0, and then uncheck the Use controller(uncheck to use minimal APIs) , next click on the Create button.
First, create a Student class in a new Model folder and paste the below code in it.
using System.ComponentModel.DataAnnotations; namespace WebAPIWithXUnit.Model { public class Student { [Key] public int Id { get; set; } public string? Name { get; set; } public int Age { get; set; } } }
Next, create AppDbContext class and paste the below code into it.
using Microsoft.EntityFrameworkCore; using MinimalAPI.Model; namespace WebAPIWithXUnit.Model { public class AppDbContext: DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Student> Students { get; set; } } }
Open appsetting.json file adds the ConnectionStrings in it.
{ "Logging": { "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" } }, "AllowedHosts": "*", "ConnectionStrings": { "DefaultConnection": "YOUR CONNECTION STRING" } }
Then apply the following command in the package manager console to create a table.
Add-Migration MyMigration
Update-Database
- Start the app using app.Run()
- Configuring routes using app.MapGet()
- Configure middleware using app.UseSwagger()
Start the App.
To start the app, and have it serve the requests, you have to call Run() on the app instance like so:
app.Run();
Configure the route.
A route and route handler is configured:
app.MapGet("/minimalapi/Students", (AppDbContext db) => { return db.Students.ToList(); });
The method MapGet() sets up a new route and takes the route “/minimalapi/Students” and a route handler, a function as the second argument (AppDbContext db) and it return the student list.
Now open your program.cs file and paste the below code in it.
using Microsoft.EntityFrameworkCore; using MinimalAPI.Services; using MinimalAPI.Services.IServices; using WebAPIWithXUnit.Model; var builder = WebApplication.CreateBuilder(args); builder.Services.AddSingleton<ITokenService>(new TokenService()); //Connection string var connectionString = builder.Configuration.GetConnectionString("DefaultConnection"); builder.Services.AddDbContext<AppDbContext>(x => x.UseSqlServer(connectionString)); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); builder.Services.AddAuthentication(); builder.Services.AddAuthorization(); var app = builder.Build(); //Get All Students app.MapGet("/minimalapi/Students", (AppDbContext db) => { return db.Students.ToList(); }); //Get All students By Id app.MapGet("/minimalApi/StudentsById", (AppDbContext db, int id) => { var students = db.Students.Find(id); return Results.Ok(students); }); //Add students app.MapPost("/minimalApi/Addstudents", (AppDbContext db, Student stud) => { db.Students.Add(stud); db.SaveChanges(); return Results.Created($"/minimalApi/StudentsById/{ stud.Id}", stud); }); //Update students app.MapPut("/minimalApi/Updatestudents/", (AppDbContext db, Student stud) => { var students = db.Students.FirstOrDefault(x => x.Id == stud.Id); students.Name = stud.Name; students.Age = stud.Age; db.Students.Update(students); db.SaveChanges(); return Results.NoContent(); }); //Delete students app.MapDelete("/minimalApi/Deltestudents/", (AppDbContext db, int id) => { var students = db.Students.Find(id); db.Students.Remove(students); db.SaveChanges(); return Results.NoContent(); }); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseAuthentication(); app.UseAuthorization(); app.Run();
That’s It.
Also check, Send Mail Using OAuth 2.0 In .Net Core 6.0 Part 1
This looks good, however, Ineed help ! Is there Part 2 to cover Services including ITokenServices.What about the U I?
Thanks
Jim