Try new experience ASP New features of minimal Web API(minimal APIS) released in the preview version of net core 6

This article was first published in Experience the new features of the minimum web API (Mini APIs) released in the preview version of ASP.NET Core 6

summary

. NET developers, I'm Rector.

A few days ago (August 10, 2021 us time), Microsoft officially released NET 6, which contains many new features and functions, such as:

  • Optimize the minimum Web API(minimal APIS) template
  • The interface implementation of IResult is added to generate common HTTP responses
  • The minimum operation supports Request,Response, etc
  • Optimized minimum host and template
  • Get Blazor component parameters from query string
  • ...

In this article, we will mainly experience the functions and features of the minimal Web API. The purpose of the minimum Web API is to help C# (or F#) back-end developers quickly create micro service projects or HTTP API services.

Same as previous ASP Net core Web API, the minimum Web API is somewhat different in startup template and framework structure. The template of the minimum Web API is quite simple. You need to write four lines of code to complete the construction of a minimum Web API project.

Let's create a minimal Web API project from scratch and experience it.

preparation

Before starting to create the minimum Web API, make sure that is installed in the development environment NET SDK 6.0. 100-preview. 7.21379. 14 (the latest version of. Net SDK). You can use it in Windows operating system NET Cli command, for example:

dotnet --info

The operation results are as follows:

If you need to view the installed in the current environment NET template, run the following command:

dotnet new -l

The operation results 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 minimum API program project

Yes There are many ways to create programs in. NET Core. You can use command-line tools to create dotnet new < template name > < project name >, or use IDE (such as Visual Studio, Rider, VS Code).

Creating minimal API projects using command line tools

Create a directory to store the project on the local disk. If the path is D: \ project \ TMP \ minimapi, open the command line tool and enter this directory. Execute the following command in the current directory:

dotnet new web MinApi

The execution results are shown in the figure below

The generated project folders and files are shown in the figure below

At this point, the creation of the smallest API project from the command line is complete.

Creating minimal API projects using Visual Studio

To create a minimum API project using Visual Studio, make sure Visual Studio 2022 17.0.0 is installed 0 preview 3.0 (current latest version).

Open the [Start Window] - [Create a new project] window of Visual Studio 2022 successively, 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 [Configure your new project] pop-up, complete the project name, location, 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)] for the Framework version, and then click the [Next] button to complete the creation of the minimum API project, as shown in the figure:

Minimum API resolution

Open the MinimalApi created just now in the IDE, and open the program in the code editor CS file, as follows:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

app.MapGet("/", () => "Hello World!");

app.Run();

It can be seen that the code of the smallest API project is very concise. If you remove the exception handling code, there are four lines 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 the launchsettings in the Properties directory JSON configuration file, modified 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 enable the project to see if it works properly. In Visual Studio 2022, press F5 to run. If the following page is opened and displayed in browsing, the minimum API project runs normally, as shown in the figure:

In the minimal API project, call webapplication. Com directly Mapget() method can complete route registration and mapping, such as adding a new route with error:

app.MapGet("/error", () => Results.Problem("error",statusCode:500));

The operation results are shown in the figure below:

WebApplication instance provides many routing mapping methods, such as HTTP request protocol: MapGet(),MapPost(),MapDelete(),MapPut(), etc.

Compared with previous ASP Net core applications, you can still use interface document components like Swagger in the smallest API project.

First, search for Swashbuckle in the Nuget package management tool, and then install Swashbuckle Aspnetcore components, as shown in the figure:

Then register Swagger's services and routes. The complete example is as follows:

using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

/// <summary>
///Add Swagger
/// </summary>
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api", Version = "v1" });

});
/// <summary>
///Register API discovery capabilities
/// </summary>
builder.Services.AddEndpointsApiExplorer();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
app.MapGet("/", () => "Hello World!");

/// <summary>
///Throw exception test
/// </summary>
app.MapGet("/throw", () => { throw new Exception("Exception occured"); });

/// <summary>
///Error page example
/// </summary>
app.MapGet("/error", () => Results.Problem("error",statusCode:500));

/// <summary>
///Register Swagger's route
/// </summary>
app.UseSwagger();
/// <summary>
///Register routes for Swagger UI
/// </summary>
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api v1"));
app.Run();

The Swagger interface after operation is shown in the figure below:

In the minimum API Application, we can also return entity objects. For example, register a route of / Customer, and then return an instance model of Customer, as follows:

using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

/// <summary>
///Add Swagger
/// </summary>
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api", Version = "v1" });

});
/// <summary>
///Register API discovery capabilities
/// </summary>
builder.Services.AddEndpointsApiExplorer();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
app.MapGet("/", () => "Hello World!");

/// <summary>
///Throw exception test
/// </summary>
app.MapGet("/throw", () => { throw new Exception("Exception occured"); });

/// <summary>
///Error page example
/// </summary>
app.MapGet("/error", () => Results.Problem("error",statusCode:500));
/// <summary>
///Return customer entity model
/// </summary>
app.MapGet("/customer", () => new Customer("Rector", "Liu"));

/// <summary>
///Register Swagger's route
/// </summary>
app.UseSwagger();
/// <summary>
///Register routes for Swagger UI
/// </summary>
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api v1"));
app.Run();

/// <summary>
///Customer entity
/// </summary>
/// <param name="FirstName"></param>
/// <param name="LastName"></param>
public record Customer(string FirstName, string LastName);

The operation results are shown in the figure below:

Well, that's the experience of the smallest Web API in this article. Codefriends will share other functions and features of the minimum Web API in subsequent articles. Please pay attention.

Tags: ASP.NET .NET

Posted by Skara on Thu, 23 Dec 2021 23:52:43 +1030