使用 OpenAPI / Swagger 记录 ASP.NET Core API





3.00/5 (3投票s)
如何使用 OpenAPI / Swagger 记录 ASP.NET Core API
目录
什么是 Swagger/ OpenAPI,以及为什么使用它来记录您的 API
Swagger 是一个开源软件框架,由一个庞大的工具生态系统支持,可帮助开发人员设计、构建、记录和使用 RESTful Web 服务。虽然大多数用户通过 Swagger UI 工具来识别 Swagger,但 Swagger 工具集包括对自动化文档、代码生成和测试用例生成的支持。
想象一下,在您的公司中,如果您的前端开发同事或其他团队在同一公司中使用您的 API,您必须花费时间回答相同的问题,即如何与此 API 集成以及规范。 通过 Swagger 或 OpenAPI,您可以解决您的问题。
OpenAPI 规范,最初称为 Swagger 规范。 这两个术语可以互换使用,但 OpenAPI 是首选术语。 一旦您开始搜索有关 OpenAPI 或 Swagger 的信息,您将很快遇到 Swagger UI、Swashbuckle、NSwag 等术语。
Swagger 是一组围绕 OpenAPI 规范构建的开源工具。
Swashbuckle.AspNetCore
帮助在 ASP.NET Core 中使用 OpenAPI。
入门
在本教程中,我将使用 ASP.NET Core 3.1 API 来演示 Swagger 的功能。 我使用 Visual Studio 2019 Community 作为我的 IDE。
ASP.NET Core API 演示简介
我们将在该 API 应用程序之上构建 Swagger,它包含使用 InMemory 提供程序的 Entity Framework Core 的简单 CRUD 操作示例启动项目。
Using the Code
安装 Swashbuckle.AspNetCore 包并注册
添加以下 NuGet 库 SwaggerDemo
Swashbuckle.AspNetCore
在 Startup.cs 文件的 ConfigureServices
和 Configure
方法中注册 swagger
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SwaggerDemo.Data;
namespace SwaggerDemo
{
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddSwaggerGen(setupAction =>
{
setupAction.SwaggerDoc(
"OpenAPISpecification",
new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "Customer API",
Version = "1"
});
});
}
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
app.UseRouting();
app.UseSwagger();
//...
}
}
}
注册后,打开以下 URL 并检查它是否正常工作
https://:53456/swagger/OpenAPISpecification/swagger.json
添加 Swagger UI
如下所示,在 Startup.cs 文件的 Configure
方法中注册 Swagger UI
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
app.UseSwagger();
app.UseSwaggerUI(setupAction =>
{
setupAction.SwaggerEndpoint
("/swagger/OpenAPISpecification/swagger.json", "Customer API");
setupAction.RoutePrefix = ""; // To available at root
});
//...
}
注册后,打开以下 URL 并检查以下 URL
https://:53456/index.html
在 Action 和类中包含 XML 文档
转到项目的属性并添加 XML 文档,如下所示
将此 XML 合并到 ConfigureServices
中
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDbContext<customercontext>(opt =>
opt.UseInMemoryDatabase("InMemoryCustomerDB")
);
services.AddSwaggerGen(setupAction =>
{
// ...
var xmlCommentsFile =
$"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlCommentsFullPath =
Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);
setupAction.IncludeXmlComments(xmlCommentsFullPath);
});
}
添加如下所示的摘要注释
/// <summary>
/// Get customer detail by id
/// </summary>
///<param name="id" />This id is unique/primary key of customer
/// <returns>Customer details with id,
/// customername and cutomer code fields
[HttpGet]
[Route("{id}", Name = "GetCustomer")] public ActionResult<customer> Get(int id) {
//... }
摘要将如下所示
忽略 XML 警告
转到项目的属性并取消 XML 警告(即 1591),如下所示
添加 API 信息和详细信息
如果需要,添加以下信息详细信息
services.AddSwaggerGen(setupAction =>
{
setupAction.SwaggerDoc(
"OpenAPISpecification",
new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "Customer API",
Version = "1",
Description ="Through this API you can access customer details",
Contact = new Microsoft.OpenApi.Models.OpenApiContact()
{
Email="amit.naik8103@gmail.com",
Name ="Amit Naik",
Url = new Uri("https://amitpnk.github.io/")
},
License = new Microsoft.OpenApi.Models.OpenApiLicense ()
{
Name ="MIT License",
Url =new Uri("https://open-source.org.cn/licenses/MIT")
}
});
var xmlCommentsFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlCommentsFullPath =
Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);
setupAction.IncludeXmlComments(xmlCommentsFullPath);
});
API Explorer 及其用法
ApiExplorer
是 ASP.NET Core MVC 之上的一个抽象,它公开有关该应用程序的元数据
将看到我们如何使用它。
添加以下 NuGet 库 SwaggerDemo
Microsoft.AspNetCore.Mvc.Api.Analyzers
在 Startup.cs 文件中注册全局级别
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(setupAction =>
{
setupAction.Filters.Add(
new ProducesResponseTypeAttribute(StatusCodes.Status400BadRequest));
setupAction.Filters.Add(
new ProducesResponseTypeAttribute(StatusCodes.Status406NotAcceptable));
setupAction.Filters.Add(
new ProducesResponseTypeAttribute
(StatusCodes.Status500InternalServerError));
setupAction.Filters.Add(
new ProducesDefaultResponseTypeAttribute());
});
//...
}
使用多个 OpenAPI
如果您的 API 模块正在增加,现在您需要在 ConfigureService
和 Configure
方法中对其进行分组,如下面的步骤所示
services.AddSwaggerGen(setupAction =>
{
setupAction.SwaggerDoc(
"OpenAPISpecificationCustomer",
new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "Customer API",
Version = "1",
Description = "Through this API you can access customer details",
Contact = new Microsoft.OpenApi.Models.OpenApiContact()
{
Email = "amit.naik8103@gmail.com",
Name = "Amit Naik",
Url = new Uri("https://amitpnk.github.io/")
},
License = new Microsoft.OpenApi.Models.OpenApiLicense()
{
Name = "MIT License",
Url = new Uri("https://open-source.org.cn/licenses/MIT")
}
});
setupAction.SwaggerDoc(
"OpenAPISpecificationWeatherDefault",
new Microsoft.OpenApi.Models.OpenApiInfo()
{
Title = "Weather default API",
Version = "1",
Description = "Through this API you can access customer details",
Contact = new Microsoft.OpenApi.Models.OpenApiContact()
{
Email = "amit.naik8103@gmail.com",
Name = "Amit Naik",
Url = new Uri("https://amitpnk.github.io/")
},
License = new Microsoft.OpenApi.Models.OpenApiLicense()
{
Name = "MIT License",
Url = new Uri("https://open-source.org.cn/licenses/MIT")
}
});
app.UseSwaggerUI(setupAction =>
{
setupAction.SwaggerEndpoint
("/swagger/OpenAPISpecificationCustomer/swagger.json", "Customer API");
setupAction.SwaggerEndpoint
("/swagger/OpenAPISpecificationWeatherDefault/swagger.json", "Weather default API");
setupAction.RoutePrefix = string.Empty;
});
[Route("api/[controller]")]
[ApiExplorerSettings(GroupName = "OpenAPISpecificationCustomer")]
[ApiController]
public class CustomerController : ControllerBase
{
// ...
}
参考文献
- https://github.com/OAI/OpenAPI-Specification
- https://github.com/domaindrivendev/Swashbuckle.AspNetCore
历史
- 2020 年 7 月 10 日:初始版本