最近教程请参考:Swashbuckle 和 ASP.NET Core 入门
Swagger 用于自动生成 API 文档。此教程基于微软官方的 Todo API,你也可以基于其他 ASP.NET Core Web API 程序。
安装包
打开程序包管理器控制台
Install-Package Swashbuckle.AspNetCore
添加并配置 Swagger 中间件
将 Swagger 生成器添加到 Startup.ConfigureServices 方法中的服务集合中:
public void ConfigureServices(IServiceCollection services){services.AddDbContext<TodoContext>(opt =>opt.UseInMemoryDatabase("TodoList"));services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);// Register the Swagger generator, defining 1 or more Swagger documentsservices.AddSwaggerGen(c =>{c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });});}
引用命名空间:
using Microsoft.OpenApi.Models;
在 Startup.Configure 方法中,启用中间件为生成的 JSON 文档和 Swagger UI 提供服务:
public void Configure(IApplicationBuilder app){app.UseDefaultFiles();app.UseStaticFiles();// Enable middleware to serve generated Swagger as a JSON endpoint.app.UseSwagger();// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),// specifying the Swagger JSON endpoint.app.UseSwaggerUI(c =>{c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");});app.UseMvc();}
在 http://localhost:
在 http://localhost:
自定义和扩展
配置信息
通过 AddSwaggerGen 方法配置作者、许可证和说明等信息:
// Register the Swagger generator, defining 1 or more Swagger documentsservices.AddSwaggerGen(c =>{c.SwaggerDoc("v1", new Info{Version = "v1",Title = "ToDo API",Description = "A simple example ASP.NET Core Web API",TermsOfService = "None",Contact = new Contact{Name = "Name xx",Email = "xx@xx.com",Url = "https://www.yuque.com/yuejiangliu/everydaydotnet"},License = new License{Name = "Use under LICX",Url = "https://example.com/license"}});});
自定义 UI
在 Configure 方法中启用静态文件中间件
app.UseStaticFiles();
前往 Swagger UI GitHub 获取 dist 文件夹的内容
创建 wwwroot/swagger/ui 文件夹,然后将 dist 文件夹的内容复制到其中
在 wwwroot/swagger/ui 中创建 custom.css
.swagger-ui .topbar {background-color: #000;border-bottom: 3px solid #547f00;}
在 index.html 中引用 custom.css
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700" rel="stylesheet"><link rel="stylesheet" type="text/css" href="./swagger-ui.css"><link rel="stylesheet" type="text/css" href="custom.css">
效果:
PS:更多有关自定义 Swagger 请参考 Docs,它们包括:
XML 注释
数据注释
描述响应类型
