前言

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 - 45 - # 按行编辑

    ​ 按行编辑 回忆上节课内容 上次我们主要就是综合运用 很好玩的,更快速的解决问题 进行计算 ctrl+a,将具体的数字加1 ctrl+x,将具体的数字减1 5ctrl+a,将具体的数字加5 一次命令 ...

  2. C# 一维数组与二维数组相互转换

    class Program { static void Main(string[] args) { double[] a = { 1, 2, 3, 4, 5, 6 }; double[,] b = R ...

  3. Notepad++实现代码格式化

    NotePad++是一个轻量级的代码编辑器,占用内存少,运行速度快,Notepad++本身是不带这个格式化功能的,但他支持NppAStyle插件完成格式化. 1. 下载插件NppAStyle.dll, ...

  4. 开源照片管理神器 PhotoPrism 安装和使用教程

    如今我们每个人都积累了海量的照片和视频,做自媒体的 UP 主们积累的照片和视频数量可能更多.面对这么多的照片和视频,我们该如何管理呢? 之前我一直用谷歌相册,因为它有很多优势,比如无限空间,支持智能整 ...

  5. 一款.NET开源、跨平台的DASH/HLS/MSS下载工具

    前言 今天大姚给大家分享一款.NET开源(MIT License).免费.跨平台的DASH/HLS/MSS下载工具,并且支持点播和直播(DASH/HLS)的内容下载:N_m3u8DL-RE. 网络流媒 ...

  6. Segment-anything学习到微调系列_SAM初步了解

    Segment-anything学习到微调系列_SAM初步了解 前言 本系列文章是博主在工作中使用SAM模型时的学习笔记,包含三部分: SAM初步理解,简单介绍模型框架,不涉及细节和代码 SAM细节理 ...

  7. windows环境xampp搭建php电商项目/搭建禅道

    windows环境xampp搭建php论坛/电商项目 一,首先下载xampp https://www.apachefriends.org/zh_cn/index.html 下载之后解压到E盘或者F盘的 ...

  8. 我用Awesome-Graphs看论文:解读GraphBolt

    GraphBolt论文:<GraphBolt: Dependency-Driven Synchronous Processing of Streaming Graphs> 前面通过文章&l ...

  9. Linux 备份命令 fsarchiver 基础使用教程

    1 安装配置 fsarchiver 使用yum安装[二者选一个即可,我使用的是下面那个]: yum install https://dl.fedoraproject.org/pub/epel/epel ...

  10. IPython notebook(Jupyter notebook) 设置密码

    本文共给出两种密码设置方法,一种为直接设置密码法(较为便捷),另一种为hash密码设置法   =================================== 第一种: 直接设置密码 注意: i ...