前言

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. Django REST framework的10个常见组件

    Django REST framework的10个常见组件: 权限组件 认证组件 访问频率限制组件 序列化组件 路由组件 视图组件 分页组件 解析器组件 渲染组件 版本组件

  2. oeasy教您玩转vim - 65 - # 批处理操作

    ​ 批处理操作 回忆上次 我们上次参数列表 arguments list 所谓参数列表指的是 vim 打开的 参数列表 参数会加载到内存中成为 buffer 参数的控制 :arga filename ...

  3. ComfyUI进阶:Comfyroll插件 (六)

    ComfyUI进阶:Comfyroll插件 (六) 前言: 学习ComfyUI是一场持久战,而Comfyroll 是一款功能强大的自定义节点集合,专为 ComfyUI 用户打造,旨在提供更加丰富和专业 ...

  4. hbuilderx打正式包所需的私钥证书的创建方法

    现在使用uniapp作为底层框架来开发app应用已经成为了很多公司的事实标准,而uniapp的开发工具hbuilderx云打包的时候,需要私钥证书和证书profile文件. 而且还需要将打包好的ipa ...

  5. linux环境部署搭建流程

    linux环境部署搭建流程 1,ubuntu/centos系统安装 2,ip网络配置 3,路由和防火墙 4,时间同步服务器 5,ssh协议配置(Windows安装xshell/secureCRT) 6 ...

  6. 【Java】在树结构中给节点追加数据

    一.功能需求 有个树状组件,展示区域层级,每个区域节点需要展示该地区下的统计信息 从来没做过,给我整不会了属实是 二.功能分析 原型有功能和老系统代码,查看源码后发现的结构框架 1.树组件是自己用ul ...

  7. 【H5】07 网页调试

    摘自: https://developer.mozilla.org/zh-CN/docs/Learn/HTML/Introduction_to_HTML/Debugging_HTML HTML 优雅明 ...

  8. Google搜索居然也搞言论封锁

    昨天的一个blog: https://www.cnblogs.com/devilmaycry812839668/p/18334275 居然被Google搜索封禁了: 老美,你的言论自由呢???怎么到了 ...

  9. 有没有使用过MindSpore的,体验怎么样啊?

    看到了一个帖子: https://www.zhihu.com/question/386352303/answer/3160948468 ================================ ...

  10. 修改linux系统时间由UTC改为CST(中国上海)时区

    Ubuntu系统 1. 将时间改为CST的中国上海时间: 命令: sudo ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime 或: sudo ...