.NET6中关于Minimal API的简单使用

Posted dotNET跨平台

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.NET6中关于Minimal API的简单使用相关的知识,希望对你有一定的参考价值。

微信公众号:趣编程ACE
收集并分享日常的.NET实战开发技巧,源码获取关注后回复 源码;
**如果觉得本公众号对您有帮助,欢迎关注

本文来自社区群粉丝投稿

.NET6中关于Minimal API的简单使用

详细文档参考官网 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0

基础代码

1using Microsoft.AspNetCore.Mvc;
 2using MinimalDemoApi.Models;
 3using MinimalDemoApi.Services;
 4
 5var builder = WebApplication.CreateBuilder(args);
 6
 7// 配置swagger
 8builder.Services.AddEndpointsApiExplorer();
 9builder.Services.AddSwaggerGen();
10
11var app = builder.Build();
12
13
14// Configure the HTTP request pipeline.
15if (app.Environment.IsDevelopment())
16
17    app.UseSwagger();
18    app.UseSwaggerUI();
19
20
21app.Run();

其实最早接触这个Miniapi的形式是在写node.js的时候,现在.net6中新增了这个功能,有着异曲同工之妙,所以如果我们项目中API数量少的话,完全可以采用这种形式开发,很精简~

示例一、

1app.MapGet("/", ()=>new Id=1,Name="Jarry");

访问根目录,页面会返回如下对象:

示例二、

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

提供一个出错接口,当访问时,可以得到如下返回信息以及响应状态码

示例三、

使用[FromServices]解决无法通过构造函数获取容器对象的问题,同时访问Get请求

1app.MapGet("/api/user",([FromServices]IUserManager userManager)=> userManager.GetUsers(););

示例四、
实现[HttpPost]请求访问接口,并通过Produces这个内置类型返回响应的状态码

1app.MapPost("/api/create",([FromServices]IUserManager userManager,[FromBody]User user)
2                                =>userManager.CreateUser(user) ? Results.Ok(): Results.BadRequest())
3                                .WithName("Create User")  // 指定名称
4                                .Produces<User>(StatusCodes.Status200OK) // 返回响应体以及状态码
5                                .Produces(StatusCodes.Status400BadRequest);

返回格式展示:

以上是关于.NET6中关于Minimal API的简单使用的主要内容,如果未能解决你的问题,请参考以下文章

简单聊下.NET6 Minimal API的使用方式

详解 .Net6 Minimal API 的使用方式

.Net Minimal API 介绍

.NET6gRPC服务端和客户端开发案例,以及minimal API服务gRPC服务和传统webapi服务的访问效率大对决

.NET 6 迁移到 Minimal API

.NET 6开发minimal api以及依赖注入的实现和代码演示