This is a step by step tutorial on how to build a minimal .NET 6.0 API from scratch with a couple of example endpoints/routes. Each step provides details on every line of code and configuration to show how it all fits together, and the resulting API can be used as a minimal starter project for building a new .NET API.
The completed API starter project is available on GitHub at https://github.com/cornflourblue/dotnet-6-minimal-api.
To develop, run and test .NET 6.0 APIs download and install the following:
The .NET CLI uses the Microsoft Build Engine (MSBuild) to build .NET projects. A .NET project file is an XML document containing MSBuild code that executes when you run the command dotnet build , and has a file extension based on the programming language used in the project (e.g. .csproj for C#, .fsproj for F#, .vbproj for VB etc).
There is a lot more to MSBuild than I can cover in this post, for full documentation see https://docs.microsoft.com/visualstudio/msbuild/msbuild.
When .NET Core was released, a new type of MSBuild project called an SDK style project was also released to simplify project files and make them much smaller. Traditionally ASP.NET projects had large and complex MSBuild project files that were managed automatically by the Visual Studio IDE, but Visual Studio isn't required for .NET Core or .NET 5.0+ projects so the new format was created to make it easier to understand and edit the files by hand.
SDK style project files are simplified because the MSBuild complexity is encapsulated in an SDK which contains a set of MSBuild properties, items, targets and tasks for building the project, all you need to do is reference the SDK for your project type.
The element is the root element of an MSBuild project file, the Sdk attribute tells MSBuild that this is an SDK style project and specifies that it's a .NET Web App with the value Microsoft.NET.Sdk.Web .
The element creates an MSBuild property named TargetFramework with the value net6.0 to configure the build for the .NET 6.0 framework. Properties in MSBuild are key/value pairs like variables in other programming languages, they are declared by adding child elements to a element.
The ImplicitUsings feature is enabled which tells the compiler to auto generate a set of global using directives based on the project type, removing the need to include a lot of common using statements. The global using statements are auto generated when you build the project and can be found in the file /obj/Debug/net6.0/WebApi.GlobalUsings.g.cs .
net6.0 enable
The .NET 6 Program file contains top-level statements which are converted by the new C# 10 compiler into a Main() method and class for the .NET program. The Main() method is the entry point for a .NET application, when an app is started it searches for the Main() method to begin execution. The top-level statements can be located anywhere in the project but are typically placed in the Program.cs file, only one file can contain top-level statements within a .NET application.
The WebApplication class handles app startup, lifetime management, web server configuration and more. A WebApplicationBuilder is first created by calling the static method WebApplication.CreateBuilder(args) , the builder is used to configure services for dependency injection (DI), a WebApplication instance is created by calling builder.Build() , the app instance is used to configure the HTTP request pipeline (middleware), then the app is started by calling app.Run() .
I wrapped the add services. and configure HTTP. sections in curly brackets <> to group them together visually, the brackets are completely optional.
Internally the WebApplicationBuilder class calls the ConfigureWebHostDefaults() extension method which configures hosting for the web app including setting Kestrel as the web server, adding host filtering middleware and enabling IIS integration. For more info on the default builder settings see https://docs.microsoft.com/aspnet/core/fundamentals/host/generic-host#default-builder-settings.
var builder = WebApplication.CreateBuilder(args); // add services to DI container < var services = builder.Services; services.AddControllers(); >var app = builder.Build(); // configure HTTP request pipeline < app.MapControllers(); >app.Run();
The appsettings.json file is the base configuration file in a .NET app that contains settings for all environments (e.g. Development, Production). You can override values for different environments by creating environment specific appsettings files (e.g. appsettings.Development.json, appsettings.Production.json).
Configuration values from the app settings file are accessed with an instance of IConfiguration which is available via .NET dependency injection (e.g. public MyConstructor(IConfiguration configuration) < . >), the config values are retrieved by key (e.g. configuration["Logging:LogLevel:Default"] ).
The Logging section of the app settings file configures the LogLevel for a couple of selected categories ( Default and Microsoft.AspNetCore ). The LogLevel sets the minimum level of message to log for each category, the default level is Information so by default all messages of level Information or higher will be logged.
The setting "Microsoft.AspNetCore": "Warning" prevents a bunch of messages from being logged for each request to the API by setting the minimum log level to Warning for all categories that begin with Microsoft.AspNetCore .
Entity classes represent the core data of a .NET app, and are commonly used with an ORM such as Entity Framework to map to data stored in a relational database (e.g. SQL Server, MySQL, SQLite etc). Entities can also be used to return HTTP response data from controller action methods, and to pass data between different parts of the application (e.g. between services and controllers).
The Product entity class represents the data for a product in the application, it contains a minimal set of properties (just Id and Name ) for testing the minimal API.
namespace WebApi.Entities; public class Product < public int Id < get; set; >public string Name < get; set; >>
Controller classes contain action methods that handle the HTTP requests sent to a .NET API. The MapControllers() method called in Program.cs above automatically creates HTTP endpoints for action methods of attribute routed controllers (controllers decorated with the [Route(". ")] attribute. All public methods of a controller are called action methods.
The ProductsController class derives from ControllerBase , a built-in .NET base class for an API controller (basically an MVC controller without view support), it provides methods and properties for handling HTTP requests including Ok() , NotFound() , Request and Response . For more info on ControllerBase see https://docs.microsoft.com/aspnet/core/web-api#controllerbase-class.
The [ApiController] attribute enables a few features designed to simplify API development, including automatic model validation and HTTP 400 response on failure, and automatic inference of the binding source (location) of parameters based on parameter type and name (e.g. [FromBody] , [FormQuery] etc). For more info see https://docs.microsoft.com/aspnet/core/web-api#apicontroller-attribute.
The [Route("[controller]")] attribute sets the route template to "[controller]" to use the controller name as the base route for all action methods (i.e. "/products" ). For more info on attribute routing see https://docs.microsoft.com/aspnet/core/mvc/controllers/routing#attribute-routing-for-rest-apis.
The private _products variable contains a hardcoded list of products to enable testing of the GetAll() and GetById() action methods, in a real world application this data would usually come from a database or another type of data repository.
The GetAll() method uses the Ok() convenience method to return an HTTP 200 OK response with a list of all products. The [HttpGet] attribute constrains the method to only match HTTP GET requests, the attribute is used without a route template parameter so it matches the base path of the controller ( "/products" ).
The GetById() method returns an Ok() response with the specified product if it exists, otherwise it returns NotFound() (HTTP response code 404 Not Found ). The [HttpGet("")] attribute constrains the method to HTTP GET requests matching the path /products/ (e.g. /products/1 , /products/2 etc), the path parameter is automatically bound to the int id parameter of the method.
The IActionResult return type represents various HTTP status codes such as 200 OK , 400 Bad Request , 404 Not Found etc. The Ok() method creates an implementation of IActionResult that produces a HTTP 200 OK response.
namespace WebApi.Controllers; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; using WebApi.Entities; [ApiController] [Route("[controller]")] public class ProductsController : ControllerBase < private List_products = new List < new Product < Name = "Milo" >, new Product < Name = "Tim Tams" >>; [HttpGet] public IActionResult GetAll() < return Ok(_products); >[HttpGet("")] public IActionResult GetById(int id) < var product = _products.Find(x =>x.Id == id); if (product == null) return NotFound(); return Ok(product); > >
Postman is a great tool for testing APIs, you can download it at https://www.postman.com/downloads.
Start the API by running dotnet run from the command line in the project root folder (where the WebApi.csproj file is located), you should see a few console messages including Now listening on: http://localhost:5000 . To enable hot reloading (restarting on file changes) use the command dotnet watch run .
NOTE: To find out how to easily launch the API in debug mode with VS Code see VS Code + .NET - Debug a .NET Web App in Visual Studio Code and skip to the step: Generate tasks.json and launch.json.
Follow these steps to fetch a list of all products from the API with Postman:
Screenshot of Postman after the request:
Follow these steps to fetch a specific product from the API with Postman:
Screenshot of Postman after the request:
Search fiverr for freelance .NET developers.