在ASP.NET Core web API中使用Swagger/OpenAPI(介绍)
介绍部分
简介
Swagger(OpenApi)是一个描述REST api的规范,与任何编程语言无关。它允许你在不看源代码的情况下理解REST API的功能以及一些API的细节
官网:Swagger.io
OpenApi和Swagger的区别
- OpenApi是一种规范
- Swagger是使用这种规范的一个工具,产品,比如OpenAPIGenerator和SwaggerUI也是。
OpenAPI规范(openapi.json)
OpenAPI规范一中描述你API功能的一个JSON文档,默认为openapi.json,内容是基于一个XML注释文件(后续提到)和你在Controller和模型类(Dtos or ViewModel)的属性注释,这个openapi.json会用于驱动SwaggerUI界面,所以这OpenApi流程的核心文件。
以下是一个简化版的例子:
| { | |
| "openapi": "3.0.1", | |
| "info": { | |
| "title": "API V1", | |
| "version": "v1" | |
| }, | |
| "paths": { | |
| "/api/Todo": { | |
| "get": { | |
| "tags": [ | |
| "Todo" | |
| ], | |
| "operationId": "ApiTodoGet", | |
| "responses": { | |
| "200": { | |
| "description": "Success", | |
| "content": { | |
| "text/plain": { | |
| "schema": { | |
| "type": "array", | |
| "items": { | |
| "$ref": "#/components/schemas/ToDoItem" | |
| } | |
| } | |
| }, | |
| "application/json": { | |
| "schema": { | |
| "type": "array", | |
| "items": { | |
| "$ref": "#/components/schemas/ToDoItem" | |
| } | |
| } | |
| }, | |
| "text/json": { | |
| "schema": { | |
| "type": "array", | |
| "items": { | |
| "$ref": "#/components/schemas/ToDoItem" | |
| } | |
| } | |
| } | |
| } | |
| } | |
| } | |
| }, | |
| "post": { | |
| … | |
| } | |
| }, | |
| "/api/Todo/{id}": { | |
| "get": { | |
| … | |
| }, | |
| "put": { | |
| … | |
| }, | |
| "delete": { | |
| … | |
| } | |
| } | |
| }, | |
| "components": { | |
| "schemas": { | |
| "ToDoItem": { | |
| "type": "object", | |
| "properties": { | |
| "id": { | |
| "type": "integer", | |
| "format": "int32" | |
| }, | |
| "name": { | |
| "type": "string", | |
| "nullable": true | |
| }, | |
| "isCompleted": { | |
| "type": "boolean" | |
| } | |
| }, | |
| "additionalProperties": false | |
| } | |
| } | |
| } | |
| } |
Swagger UI
Swagger UI基于Web页面,它提供了一些关于api服务的一些信息,这些信息来源于前面的openapi.json。Swashbuckle和NSwag都包含了一个内嵌的Swagger UI,您可以在ASP.NET Core程序中通过注册中间件调用的方式使用它。它长这样(Version 3):
漫思
浙公网安备 33010602011771号