This article was first published on - "It only takes 4 lines of code to create an API service! ! ! Try to experience the new features of the minimal APIS released in the preview version of ASP.NET Core 6 "
Overview
Hello .NET developers, my name is Rector.
A few days ago (August 10, 2021, US time), Microsoft officially released the seventh preview version of .NET 6, which contains many new features and functions, such as:
- Optimize the minimal API (minimal APIS) template
- Added IResult interface implementation for generating common HTTP responses
- Minimal operation supports Request, Response, etc.
- Optimized the smallest host and template
- Get Blazor component parameters from the query string
- ...
In this article, we mainly come to experience the functions and features of the minimal Web API. The purpose of minimal Web API is mainly to help C# (or F#) back-end developers quickly create microservice projects or HTTP API services.
Compared with the previous ASP.NET Core Web API, the minimal Web API is somewhat different in startup template and framework structure. The minimal Web API template is quite concise, you need to write 4 lines of code to complete a minimal Web API project.
Let's create a minimal Web API project from scratch and experience it.
Ready to work
Before starting to create a minimal Web API, please make sure that the .NET SDK 6.0.100-preview.7.21379.14 (currently the latest .NET SDK version) has been installed in the development environment. In the Windows operating system, you can use .NET Cli Command to view, such as:
dotnet --info
The results of the operation are as follows:
If you need to view the .NET templates installed in the current environment, run the following command:
dotnet new -l
The results of the operation are as follows:
Template Name Short Name Language Tags
-------------------------------------------- ------------------- ---------- --------------------------
ASP.NET Core Empty web [C#],F# Web/Empty
ASP.NET Core gRPC Service grpc [C#] Web/gRPC
ASP.NET Core Web API webapi [C#],F# Web/WebAPI
ASP.NET Core Web App razor,webapp [C#] Web/MVC/Razor Pages
ASP.NET Core Web App (Model-View-Controller) mvc [C#],F# Web/MVC
ASP.NET Core with Angular angular [C#] Web/MVC/SPA
ASP.NET Core with React.js react [C#] Web/MVC/SPA
ASP.NET Core with React.js and Redux reactredux [C#] Web/MVC/SPA
Blazor Server App blazorserver [C#] Web/Blazor
Blazor WebAssembly App blazorwasm [C#] Web/Blazor/WebAssembly/PWA
Class Library classlib [C#],F#,VB Common/Library
Console Application console [C#],F#,VB Common/Console
dotnet gitignore file gitignore Config
Dotnet local tool manifest file tool-manifest Config
global.json file globaljson Config
MSTest Test Project mstest [C#],F#,VB Test/MSTest
MVC ViewImports viewimports [C#] Web/ASP.NET
MVC ViewStart viewstart [C#] Web/ASP.NET
NuGet Config nugetconfig Config
NUnit 3 Test Item nunit-test [C#],F#,VB Test/NUnit
NUnit 3 Test Project nunit [C#],F#,VB Test/NUnit
Protocol Buffer File proto Web/gRPC
Razor Class Library razorclasslib [C#] Web/Razor/Library
Razor Component razorcomponent [C#] Web/ASP.NET
Razor Page page [C#] Web/ASP.NET
Solution File sln Solution
Web Config webconfig Config
Windows Forms App winforms [C#],VB Common/WinForms
Windows Forms Class Library winformslib [C#],VB Common/WinForms
Windows Forms Control Library winformscontrollib [C#],VB Common/WinForms
Worker Service worker [C#],F# Common/Worker/Web
WPF Application wpf [C#],VB Common/WPF
WPF Class library wpflib [C#],VB Common/WPF
WPF Custom Control Library wpfcustomcontrollib [C#],VB Common/WPF
WPF User Control Library wpfusercontrollib [C#],VB Common/WPF
xUnit Test Project xunit [C#],F#,VB Test/xUnit
Create a minimal API program project
There are many ways to create a program in .NET Core, you can use the command line tool to execute dotnet new <template name> <project name> to create, or you can use IDE (such as: Visual Studio, Rider, VS Code) to create.
Use command line tools to create a minimal API project
Create a directory to store the project on the local disk. If the path is D:\Project\tmp\MinimalApi
, open the command line tool and enter this directory, and execute the following command in the current directory:
dotnet new web MinApi
The execution result is as shown in the figure below
The generated project folder and files are as shown in the figure below
At this point, creating a minimal API project by command line is complete.
Use Visual Studio to create a minimal API project
To use Visual Studio to create a minimal API project, please make sure that Visual Studio 2022 17.0.0 Preview 3.0 (currently the latest version) is installed.
Open the [Start Window]->[Create a new project] window of Visual Studio 2022 in turn, select the [ASP.NET Core Empty] project template from the list of installed templates on the right, and then click the [Next] button, as shown in the figure:
In the pop-up [Configure your new project], complete the Project name (project name), Location (location), Solution name (solution name) and other information, and then click the [Next] button, as shown in the figure:
In the pop-up [Additional Information] window, select [.NET 6.0(Preview)] as the version of Framework, and then click the [Next] button to complete the creation of the minimal API project, as shown in the figure:
Minimal API analysis
Open the MinimalApi just created in the IDE, and open the Program.cs
file in the code editor, as follows:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.MapGet("/", () => "Hello World!");
app.Run();
As you can see, the code of the smallest API project is very concise. If you remove the exception handling code, there are 4 lines of code left, as follows:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();
In order not to enable https, let's modify launchSettings.json
Properties
directory. The modified configuration file is as follows:
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:2200",
"sslPort": 0
}
},
"profiles": {
"MinimalApi": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:2200",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Then start the project to see if it can run normally. In Visual Studio 2022, press F5 to run. If you open and display the following page in the browser, it means that the minimal API project is running normally, as shown in the figure:
In the minimal API project, WebApplication.MapGet()
method to complete the registration and mapping of the route error
app.MapGet("/error", () => Results.Problem("错误",statusCode:500));
The results of the operation are shown in the figure:
WebApplication
instance provides many routing mapping methods, such as HTTP request protocol:MapGet()
,MapPost()
,MapDelete()
,MapPut()
and so on.
As with previous ASP.NET Core applications, you can still use interface documentation components like Swagger in minimal API projects.
Swashbuckle
in the Nuget package management tool, and then install the Swashbuckle.AspNetCore
component, as shown in the figure:
Then register Swagger's service and routing, the complete example is as follows:
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
/// <summary>
/// 添加Swagger
/// </summary>
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api", Version = "v1" });
});
/// <summary>
/// 注册API发现功能
/// </summary>
builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.MapGet("/", () => "Hello World!");
/// <summary>
/// 抛出异常测试
/// </summary>
app.MapGet("/throw", () => { throw new Exception("Exception occured"); });
/// <summary>
/// 错误页面示例
/// </summary>
app.MapGet("/error", () => Results.Problem("错误",statusCode:500));
/// <summary>
/// 注册Swagger的路由
/// </summary>
app.UseSwagger();
/// <summary>
/// 注册Swagger UI的路由
/// </summary>
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api v1"));
app.Run();
The Swagger interface after running is shown in the figure:
In the minimal API application, we can also return entity objects, such as registering a /customer
, and then returning an Customer
, as follows:
using Microsoft.OpenApi.Models;
var builder = WebApplication.CreateBuilder(args);
/// <summary>
/// 添加Swagger
/// </summary>
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api", Version = "v1" });
});
/// <summary>
/// 注册API发现功能
/// </summary>
builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.MapGet("/", () => "Hello World!");
/// <summary>
/// 抛出异常测试
/// </summary>
app.MapGet("/throw", () => { throw new Exception("Exception occured"); });
/// <summary>
/// 错误页面示例
/// </summary>
app.MapGet("/error", () => Results.Problem("错误",statusCode:500));
/// <summary>
/// 返回客户实体模型
/// </summary>
app.MapGet("/customer", () => new Customer("Rector", "Liu"));
/// <summary>
/// 注册Swagger的路由
/// </summary>
app.UseSwagger();
/// <summary>
/// 注册Swagger UI的路由
/// </summary>
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api v1"));
app.Run();
/// <summary>
/// 客户实体
/// </summary>
/// <param name="FirstName"></param>
/// <param name="LastName"></param>
public record Customer(string FirstName, string LastName);
The results of the operation are shown in the figure:
Well, this article has the experience of minimal Web API. Please stay tuned for other functions and features of Mini Web API that will be shared by Codeyou.com in subsequent articles.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。