前言

Swagger (OpenAPI) 是一套 Web API 文档规范.

ASP.NET Core 有 2 个 Library 可用来实现 Swagger.

Swashbuckle 和 NSwag.

NSwag 能直接生成 client code 比如 JS, TypeScript 等等, 但 ASP.NET Core 默认的模板使用的是 Swashbuckle.

主要参考

Get started with Swashbuckle and ASP.NET Core

Controller action return types in ASP.NET Core web API

创建 Web API 模板

dotnet new webapi -o TestSwagger

ASP.NET Core 6.0 开始 Web API 模板自带了 Swagger. 所以不需要自己装 nuget

运行起来长这样 https://localhost:7055/swagger/index.html

配置 docs

services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1.0", new OpenApiInfo
{
Title = "Project Web API",
Version = "v1.0",
Description = "Project Web API version 1.0",
Contact = new OpenApiContact
{
Name = "Derrick Yam",
Email = "hengkeat87@gmail.com",
},
});
});

UI Endpoint

app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint("/swagger/v1.0/swagger.json", "Project Web API v1.0");
options.DocExpansion(DocExpansion.None); // 默认是自动开, 我不喜欢, 所以关掉它
});

开启 XML comments

打开 project.csproj, 添加 2 行, Nowarn 是去掉警告, 不然会很吵.

<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

添加

services.AddSwaggerGen(options =>
{
...
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
options.IncludeXmlComments(xmlPath);
});

Controller > Action

Action 大概长这样

/// <summary>
/// some summary here...
/// </summary>
/// <remarks>
/// some remark here...
/// </remarks>
/// <param name="dto">Customer information</param>
/// <returns>A newly created customer</returns>
/// <response code="201">Returns the newly created customer</response>
/// <response code="400">When DTO invalid</response>
[HttpPost("customers")]
[Consumes(MediaTypeNames.Application.Json)] // 接收 json
[Produces(MediaTypeNames.Application.Json)] // 返回 json
[ProducesResponseType(StatusCodes.Status201Created, Type = typeof(Customer))] // 有可能返回 200, 可以定义类型, 或者用 ActionResult 定义(那这里就不需要了)
[ProducesResponseType(StatusCodes.Status400BadRequest)] // 有可能返回 400
public async Task<ActionResult<Customer>> CreateCustomerAsync(
[FromBody] CreateCustomerDTO dto
)
{
...
return CreatedAtAction("GetById", new { customerId = customer.CustomerId }, customer);
}

关于 return type 可以看这篇, 这些注释最终就会出现在 docs 里.

ODataController action 长这样 (just example 不要管 versioning 哪些先)

[ApiController]
[ApiVersion("1.0")]
public class CustomersController : ODataController
{
private readonly ApplicationDbContext _db; public CustomersController(
ApplicationDbContext db
)
{
_db = db;
} [HttpGet("customers")]
[Produces(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status200OK)]
[EnableQuery]
public ActionResult<IEnumerable<Customer>> GetCustomers()
{
return Ok(_db.Customers);
} [HttpGet("customers/{id}")]
[Produces(MediaTypeNames.Application.Json)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[EnableQuery]
public ActionResult<Customer> GetByIdAsync(int id)
{
return Ok(SingleResult.Create(_db.Customers.Where(c => c.CustomerId == id)));
}
}

ASP.NET Core – Swagger OpenAPI (Swashbuckle)的更多相关文章

  1. Asp.Net Core: Swagger 与 Identity Server 4

    Swagger不用多说,可以自动生成Web Api的接口文档和客户端调用代码,方便开发人员进行测试.通常我们只需要几行代码就可以实现这个功能: ... builder.Services.AddSwag ...

  2. ASP.NET Core Swagger接入使用IdentityServer4 的 WebApi

    写在前面 是这样的,我们现在接口使用了Ocelot做网关,Ocelot里面集成了基于IdentityServer4开发的授权中心用于对Api资源的保护.问题来了,我们的Api用了SwaggerUI做接 ...

  3. asp.net core swagger使用及注意事项

    Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.是一款RESTFUL接口的文档在线自动生成+功能测试软件.主要目的是构建标准的.稳定的.可重 ...

  4. 记Asp.Net Core Swagger 使用 并带域接口处理

    引用作者原话:Asp.Net的WebApi中使用Swagger作为说明和测试的页面是非常不错的,比起WebApiTestClient来至少在界面上的很大的提升.但是使用Swagger时如果只是一般的控 ...

  5. ASP.NET CORE Swagger

    Package 添加并配置Swagger中间件 将Swagger生成器添加到方法中的服务集合中Startup.ConfigureServices: public void ConfigureServi ...

  6. Asp.Net Core Swagger 接口分组(支持接口一对多暴露)

    开始之前,先介绍下swagger常用方法. services.AddSwaggerGen    //添加swagger中间件 c.SwaggerDoc  //配置swagger文档,也就是右上角的下拉 ...

  7. ASP.NET Core Swagger 显示接口注释

    在Startup中 services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { Title ...

  8. asp.net core使用Swashbuckle.AspNetCore(swagger)生成接口文档

    asp.net core中使用Swashbuckle.AspNetCore(swagger)生成接口文档 Swashbuckle.AspNetCore:swagger的asp.net core实现 项 ...

  9. asp.net core web api 生成 swagger 文档

    asp.net core web api 生成 swagger 文档 Intro 在前后端分离的开发模式下,文档就显得比较重要,哪个接口要传哪些参数,如果一两个接口还好,口头上直接沟通好就可以了,如果 ...

  10. 如何在 asp.net core 的中间件中返回具体的页面

    前言 在 asp.net core 中,存在着中间件这一概念,在中间件中,我们可以比过滤器更早的介入到 http 请求管道,从而实现对每一次的 http 请求.响应做切面处理,从而实现一些特殊的功能 ...

随机推荐

  1. oeasy教您玩转vim - 61- # 编辑过程

    ​ 编辑过程 回忆上次 vi可以加各种参数 vi +4 oeasy.txt vi +/shiyanlou vi +%s/shiyanlou/oeasy/g oeasy.txt vi可以接收stdin的 ...

  2. oeasy教您玩转vim - 69 - # 折叠folding入门

    ​ 折叠入门 回忆上次 上次学习了一种新的容器 tabs选项卡 tabs选项卡 包含多个选项卡tab 可以列两个tab 一个编写文件 一个执行指令 互不影响 每个 tab选项卡 还可以对应多个wind ...

  3. 题解:P10537 [APIO2024] 九月

    题解:P10537 [APIO2024] 九月 题意 在一个树上,在 \(k\) 天内有 \(n-1\) 个节点掉落,会有 \(m\) 个记录者记录掉落的情况,每一天每一个人会以任意的顺序记录当天的掉 ...

  4. httpclient,轻量级idea集成测试工具

    优点:不用新开一个网页,具有测试数据保存功能,不需要配置即用(对比swagger)     不会特别占内存(对比postman) 使用方法:idea中安装插件 controller方法中点击 选择对应 ...

  5. ChatGPT的作用(附示例)

    ChatGPT介绍(内容由ChatGPT生成) ChatGPT是一款基于GPT(生成式预测网络)的聊天机器人,它可以根据用户输入自动生成相应的回复. GPT是由OpenAI开发的一种预测网络模型,其中 ...

  6. Pulsar客户端消费模式揭秘:Go 语言实现 ZeroQueueConsumer

    前段时间在 pulsar-client-go 社区里看到这么一个 issue: import "github.com/apache/pulsar-client-go/pulsar" ...

  7. linux常用命令(每日积累)

    linux查看应用程序的进程号和端口号 lsof -i :port,查看指定端口运行的程序,同时还有当前连接. netstat -nupl  (UDP类型的端口)netstat -ntpl  (TCP ...

  8. 【Java】JNDI实现

    前提情要: 培训的时候都没讲过,也是书上看到过这么个东西,进公司干外包的第二个项目就用了这个鬼东西 自学也不是没尝试过实现,结果各种失败,还找不到问题所在,索性不写了 JNDI实现参考: 目前参考这篇 ...

  9. 【MySQL】29 索引

    MySQL是一个关系型的数据库 使用标准的SQL数据格语言格式 支持大型数据库,处理千万级别的记录数据 允许多系统运行,支持多种编程语言连接 最重要的一点是MySQL允许定制,采用GPL协议,允许修改 ...

  10. 第四范式开源强化学习框架——OpenRL

    维护者信息: 知乎地址: https://www.zhihu.com/people/huangshiyu.me 个人主页: http://tartrl.cn/people/huangshiyu/ Gi ...