Create an ASP.NET Core Minimal API in C#

An ASP.NET Core Minimal API is a lightweight approach to develop web APIs using ASP.NET Core. It provides a simpler way to create APIs with minimal boilerplate code, focusing on the essentials for handling HTTP requests and responses.

Here in the post, We will discuss and demostrate how to develop web api using ASP.NET minimal api technology.

Getting Started

Creating an ASP.NET Core Minimal API in Visual Studio is a straightforward process. I'll guide you through the steps to create the Minimal API using Visual Studio.

Prerequisites:

  1. Visual Studio 2022 or later installed.
  2. .NET 6.0 or higher SDK installed.

Demonstration

In this example, we will create a .NET Minimal API to perform CRUD operations on students. We will not use any database or database helper libraries to interact with the database. Here in below are the stpes to create .net core minimal api:

Steps to create an ASP.NET Core Minimal API in Visual Studio:

Create a New Project
  • Launch Visual Studio on your machine.
  • Click on "Create a new project".
  • In the search box, type ASP.NET Core Web API and select ASP.NET Core Web API template.
  • Click Next.
Configure Your Project
  • Project name: Enter a name for your project, e.g., MyMinimalAPI.
  • Location: Choose the directory where you want to save the project.
  • Solution name: This will be auto-filled with your project name, but you can change it if needed.
  • Click Create.
Select .NET Version
  • Choose .NET 6.0 , .NET 7.0 or .NET 8.0 (if available). For a minimal API, this example will use .NET 8.0, but you can select the latest available version.
  • Authentication Type: Select None (since we're not focusing on authentication for this simple API).
  • Click Create.
Add Model Class to Minimal API

A model class is added here to store student information. Follow the steps below to add the model class.

  1. In Solution Explorer, right-click the project.
  2. Select Add > New Folder. Name the folder Models.
  3. Right-click the Models folder and select Add > Class.
  4. Name the class StudentModel and select Add.
  5. Replace the template code with the following:
     namespace HelloWorldAPI.Models  
     {  
       public class StudentModel  
       {  
         public int Id { get; set; }  
         public string? Name { get; set; }  
         public string ClassName { get; set; }  
       }  
     }  
    
Minimal API Swagger

Here, we will see how to enable Swagger in the Minimal API. Details about Swagger are given below. The SwaggerGen package is required to be installed in order to enable Swagger. here are the stepps to download ghe Swaggergen package:

  • Right-click on the project name in the Solution Explorer.
  • Select Manage NuGet Packages.
  • In the NuGet Package Manager window, go to the Browse tab.
  • In the search bar, type Swashbuckle.AspNetCore (this package includes SwaggerGen).
  • Press Enter to search.
  • From the search results, find Swashbuckle.AspNetCore.
  • Click on it to view the details.
  • Click the Install button.
  • A pop-up window will appear asking you to confirm the installation and accept the license agreements.
  • Click OK to proceed.
Modify Program.cs for Minimal API

In a Minimal API, you don't need controllers, and the program setup can be written in a very compact way. Open the Program.cs file, and modify it like this:

1:  using MyMinimalAPI;  
2:  var builder = WebApplication.CreateBuilder(args);  
3:  //minimal api swagger  
4:  builder.Services.AddEndpointsApiExplorer();  
5:  builder.Services.AddSwaggerGen();  
6:  builder.Services.AddSingleton<StudentContext>();  
7:  var app = builder.Build();  
8:  // Configure the HTTP request pipeline  
9:  if (app.Environment.IsDevelopment())  
10:  {  
11:    app.UseSwagger();  
12:    app.UseSwaggerUI();  
13:  }  
14:  app.MapGet("/", () => "Hello, World!");  
15:  app.MapGet("/GetStudents", (StudentContext context) =>  
16:   Results.Ok(context.Students));  
17:  app.MapGet("/GetStudent", (StudentContext context, string name) =>  
18:  {  
19:    StudentModel student = context.GetStudent(name);  
20:    if (student != null)  
21:    {  
22:      Results.Ok(student);  
23:      //Results.Ok($"Student Name: {student.Name} Class: {student.ClassName}");  
24:    }  
25:    else { Results.NotFound(); }  
26:  });  
27:  app.MapPost("/AddStudent", (StudentContext context, int studentId, string studentName, string className) =>  
28:  {  
29:    int res = context.Add(studentId, studentName, className);  
30:    if (res > 0)  
31:      Results.Ok("Student detail save successfully");  
32:    else  
33:      Results.Ok("Failes to save");  
34:  });  
35:  app.Run();  

Explanation of the code:
  • WebApplication.CreateBuilder(args): Creates the application builder that sets up services and configurations.
  • app.MapGet("/"): Defines a GET route that returns "Hello, World!".
  • app.MapGet("/GetStudents"): A GET route that list outs students.
  • app.MapGet("/GetStudent"): A GET route that accepts a JSON object and returns sudent detail.
  • app.MapGet("/AddStudent"): A POST route that accepts a JSON object and saves in student list.
  • Swagger: If you want to test your API easily, Swagger is enabled with the code in Line#[5], Line#[11] and Line#[12] to allow testing through a browser.

Test the API

  • Open your browser and navigate to https://localhost:7062/ to see the "Hello, World!" message.
  • To test the other endpoints, you can use tools like Postman or Swagger UI (which will be available if you're running in development mode).
  • Swagger UI will be available at https://localhost:7062/swagger where you can interact with the API.

You have now created a minimal API in ASP.NET Core using Visual Studio! This minimal approach doesn't require controllers and provides a lightweight way to define endpoints in a very concise manner. The API is also easily testable via Swagger UI or other tools like Postman.

Endpoints Example

GET https://localhost:7062/GetStudents
Result
 [{"id":1,"name":"Kailash","className":"I"},  
 {"id":2,"name":"Nidhi","className":"I"},  
 {"id":3,"name":"Mini","className":"I"},  
 {"id":4,"name":"Ani","className":"I"},  
 {"id":5,"name":"Puja","className":"I"},  
 {"id":6,"name":"Kalyani","className":"I"},  
 {"id":7,"name":"Krishna","className":"I"},  
 {"id":8,"name":"Nila","className":"I"}]  

GET https://localhost:7062/GetStudent?name=Kailash
Result
 {"id":1,"name":"Kailash","className":"I"}  

Minimal API Features:

  • No Controllers Needed: Unlike traditional ASP.NET Core APIs that require controllers and actions, Minimal APIs work directly in the Program.cs file.
  • Endpoint Definitions: Endpoints are defined directly using methods like MapGet, MapPost, etc.
  • Request Models: You can easily bind incoming requests to models via parameters (e.g., query parameters, route parameters, or body).
  • Lightweight: Minimal APIs are great for small APIs, microservices, or when you want to avoid a lot of unnecessary overhead.
  • Built-in Dependency Injection: You can still use dependency injection (DI) with Minimal APIs just as you would in a full MVC API.
  • Swagger Support: Adding Swagger support is straightforward with AddEndpointsApiExplorer() and AddSwaggerGen().
  • Starting from ASP.NET Core 6, Minimal APIs were introduced to make it easier to build APIs by reducing the amount of configuration and code required.

Swagger in ASP.NET Core Minimal API

Swagger is a tool for documenting and testing your REST APIs. It automatically generates interactive API documentation based on your code, making it easier to understand and test your API endpoints. In ASP.NET Core, Swashbuckle.AspNetCore is the library that helps enable Swagger support.

Summary

ASP.NET Core Minimal APIs offer a simple and efficient way to build web APIs. They are especially useful for small or microservice-based applications, where you don't need the complexity of a full MVC-style controller setup.

Thanks

Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

1 Comments

Previous Post Next Post

نموذج الاتصال