ASP.NET Core – Swagger OpenAPI (Swashbuckle)
前言
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)的更多相关文章
- Asp.Net Core: Swagger 与 Identity Server 4
Swagger不用多说,可以自动生成Web Api的接口文档和客户端调用代码,方便开发人员进行测试.通常我们只需要几行代码就可以实现这个功能: ... builder.Services.AddSwag ...
- ASP.NET Core Swagger接入使用IdentityServer4 的 WebApi
写在前面 是这样的,我们现在接口使用了Ocelot做网关,Ocelot里面集成了基于IdentityServer4开发的授权中心用于对Api资源的保护.问题来了,我们的Api用了SwaggerUI做接 ...
- asp.net core swagger使用及注意事项
Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.是一款RESTFUL接口的文档在线自动生成+功能测试软件.主要目的是构建标准的.稳定的.可重 ...
- 记Asp.Net Core Swagger 使用 并带域接口处理
引用作者原话:Asp.Net的WebApi中使用Swagger作为说明和测试的页面是非常不错的,比起WebApiTestClient来至少在界面上的很大的提升.但是使用Swagger时如果只是一般的控 ...
- ASP.NET CORE Swagger
Package 添加并配置Swagger中间件 将Swagger生成器添加到方法中的服务集合中Startup.ConfigureServices: public void ConfigureServi ...
- Asp.Net Core Swagger 接口分组(支持接口一对多暴露)
开始之前,先介绍下swagger常用方法. services.AddSwaggerGen //添加swagger中间件 c.SwaggerDoc //配置swagger文档,也就是右上角的下拉 ...
- ASP.NET Core Swagger 显示接口注释
在Startup中 services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Info { Title ...
- asp.net core使用Swashbuckle.AspNetCore(swagger)生成接口文档
asp.net core中使用Swashbuckle.AspNetCore(swagger)生成接口文档 Swashbuckle.AspNetCore:swagger的asp.net core实现 项 ...
- asp.net core web api 生成 swagger 文档
asp.net core web api 生成 swagger 文档 Intro 在前后端分离的开发模式下,文档就显得比较重要,哪个接口要传哪些参数,如果一两个接口还好,口头上直接沟通好就可以了,如果 ...
- 如何在 asp.net core 的中间件中返回具体的页面
前言 在 asp.net core 中,存在着中间件这一概念,在中间件中,我们可以比过滤器更早的介入到 http 请求管道,从而实现对每一次的 http 请求.响应做切面处理,从而实现一些特殊的功能 ...
随机推荐
- django 信号 新增和删除信的合用
from django.db.models.signals import post_save, post_delete from django.dispatch import receiver fro ...
- vue项目锚点定位+滚动定位
功能: HTML: js: scrollEvent(e) { let scrollItems = document.querySelectorAll('.condition-container') f ...
- 4、SpringBoot2之整合SpringMVC
创建名为springboot_springmvc的新module,过程参考3.1节 4.1.重要的配置参数 在 spring boot 中,提供了许多和 web 相关的配置参数(详见官方文档),其中有 ...
- 【FastDFS】环境搭建 02 测试
自带工具测试: 编辑客户端配置文件: vim client.conf 配置完成后,随便上传一个图片到root目录下 运行FastFDS文件上传程序,并将客户端配置文件作为加载参数1,要上传的图片文件位 ...
- 工业AI制造:铝合金冲压、压铸工艺流程 —— 模具参数调整,以满足所需的规格和质量要求
压铸操作工艺流程作步骤: 模具安装 → 调试 →清理预热模具 → 喷刷涂料 → 合模 → 涂料准备 → 涂料配制 → 压铸 → 冷却与凝固 → 开模 → 顶出铸件 → 质量检验 → 成品 → 废品 → ...
- 深度学习框架theano下的batch_norm实现代码——强化学习框架rllab
深度学习框架theano下的batch_norm实现代码--强化学习框架rllab # encoding: utf-8 import lasagne.layers as L import lasagn ...
- 飞书Webhook触发操作指南,实现事件驱动型工作流自动化
本文提供了利用数据触发Feishu Webhook的具体操作指南,包括Webhook的设置以及编写触发代码的方法,为读者提供了实践参考,希望能帮助解决你目前遇到的问题. 描述 用于使用数据触发 Fei ...
- 在LCD上的任意位置显示一张任意大小的jpg图片
/************************************************* * * file name:lcdshowjpg.c * author :momolyl@126. ...
- JavaScript魔法:在线Excel附件上传与下载的完美解决方案
最新技术资源(建议收藏) https://www.grapecity.com.cn/resources/ 前言 在本地使用Excel时,经常会有需要在Excel中添加一些附件文件的需求,例如在Exce ...
- 代码随想录Day17
654.最大二叉树 给定一个不重复的整数数组 nums . 最大二叉树 可以用下面的算法从 nums 递归地构建: 创建一个根节点,其值为 nums 中的最大值. 递归地在最大值 左边 的 子数组前缀 ...