6

创建API服务最小只要4行代码!!!尝新体验ASP.NET Core 6预览版本中的最小Web API(mi...

 3 years ago
source link: https://www.cnblogs.com/bobositlife/p/aspnet-core-6-minimal-web-api.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

创建API服务最小只要4行代码!!!尝新体验ASP.NET Core 6预览版本中的最小Web API(minimal APIS)新特性

本文首发于《创建API服务最小只要4行代码!!!尝新体验ASP.NET Core 6预览版本中的最小Web API(minimal APIS)新特性》

.NET开发者们大家好,我是Rector。

几天前(美国时间2021年8月10日),微软官方发布了.NET 6的第7个预览版,其中包含了很多新的特性和功能,比如:

  • 优化最小Web API(minimal APIS)模板
  • 为生成常用HTTP响应添加了IResult的接口实现
  • 最小操作支持Request,Response等
  • 优化了最小主机、模板
  • 从查询字符串中获取Blazor组件参数

本文我们主要来体验最小Web API的功能和特性。最小Web API的目的主要是帮助C#(或者F#)后端开发者快速创建微服务项目或者HTTP API服务。

与之前的ASP.NET Core Web API相比,最小Web API在启动模板和框架结构上都有些不同。最小Web API的模板相当简洁,你几需要写4行代码便可完成一个最小Web API项目的搭建。

下面我们从头开始创建一个最小Web API项目并体验。

在开始创建最小Web API之前,请确保开发环境中已安装了.NET SDK 6.0.100-preview.7.21379.14(当前最新的.NET SDK版本),在Windows操作系统中,你可以使用.NET Cli命令来查看,比如:

dotnet --info

运行结果如下图:

如果需要查看当前环境已安装的.NET模板,运行如下命令:

dotnet new -l

运行结果如下:

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

创建最小API程序项目

在.NET Core中创建程序的方式有多种,可以使用命令行工具执行dotnet new <模板名称> <项目名称>创建,也可以使用IDE(如:Visual Studio, Rider, VS Code)来创建。

使用命令行工具创建最小API项目

在本地磁盘创建一个存储项目的目录,假如路径为D:\Project\tmp\MinimalApi,打开命令行工具并进入此目录,在当前目录下执行如下命令:

dotnet new web MinApi

执行结果如下图

生成的项目文件夹和文件如下图

至此,以命令行方式创建最小API项目即完成。

使用Visual Studio创建最小API项目

使用Visual Studio创建最小API项目,请确保已安装Visual Studio 2022 17.0.0 Preview 3.0(当前最新版本)。

依次打开Visual Studio 2022的【Start Window】->【Create a new project】窗口,在右侧的已安装模板列表中选择【ASP.NET Core Empty】项目模板,之后点击[Next]按钮,如图:

在弹出的【Configure your new project】中,完善Project name(项目名称),Location(位置),Solution name(解决方案名称)等信息,然后点击[Next]按钮,如图:

在弹出的【Additional Information】窗口中,Framework的版本选择[.NET 6.0(Preview)],然后点击[Next]按钮,以完成最小API项目的创建,如图:

最小API解析

在IDE中打开刚才创建的MinimalApi,并在代码编辑器中打开Program.cs文件,如下:

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

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

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

app.Run();

可以看到,最小API项目的代码非常简洁,如果去掉其中的异常处理代码,就还剩4行代码了,如下:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello World!");
app.Run();

为了不启用https,我们修改一下位于Properties目录中的launchSettings.json配置文件,修改后如下:

{
  "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"
      }
    }
  }
}

然后启用项目,看是否能正常运行起来。在Visual Studio 2022中,按F5运行,如果在浏览中打开并显示如下页面,说明最小API项目运行正常,如图:

在最小API项目中,直接调用WebApplication.MapGet()方法即可完成路由的注册和映射,如新增一个error的路由:

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

运行结果如图:

WebApplication实例提供了很多路由映射的方法,比如HTTP请求协议:MapGet(),MapPost(),MapDelete(),MapPut()等等。

与以往的ASP.NET Core应用程序相同,在最小API项目中,你仍然可以使用像Swagger这样的接口文档组件。

首先,在Nuget包管理工具中搜索Swashbuckle,然后安装Swashbuckle.AspNetCore组件,如图:

然后注册Swagger的服务和路由,完整的示例如下:

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();

运行后的Swagger界面如图:

在最小API应用程序中,我们同样也可以返回实体对象,比如:注册一个/customer的路由,然后返回一个Customer的实例模型,如下:

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);

运行结果如图:

好了,本文对最小Web API的体验到此。码友网将在后续的文章中为大家分享的关于最小Web API的其他功能和特性,敬请关注。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK