⒈新建ASP.NET Core WebAPi项目
⒉添加 NuGet 包
Install-Package Swashbuckle.AspNetCore
⒊Startup中配置
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading.Tasks; 5 using Microsoft.AspNetCore.Builder; 6 using Microsoft.AspNetCore.Hosting; 7 using Microsoft.AspNetCore.Mvc; 8 using Microsoft.Extensions.Configuration; 9 using Microsoft.Extensions.DependencyInjection; 10 using Microsoft.Extensions.Logging; 11 using Microsoft.Extensions.Options; 12 using Swashbuckle.AspNetCore.Swagger; 13 14 namespace SwaggerDemo 15 { 16 public class Startup 17 { 18 public Startup(IConfiguration configuration) 19 { 20 Configuration = configuration; 21 } 22 23 public IConfiguration Configuration { get; } 24 25 // This method gets called by the runtime. Use this method to add services to the container. 26 public void ConfigureServices(IServiceCollection services) 27 { 28 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 29 30 //注册Swagger生成器,定义一个和多个Swagger 文档 31 services.AddSwaggerGen(option => 32 { 33 //配置第一个Doc 34 option.SwaggerDoc("v1", new Info 35 { 36 Version = "v1", 37 Title = "My API_1" 38 }); 39 }); 40 } 41 42 // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 43 public void Configure(IApplicationBuilder app, IHostingEnvironment env) 44 { 45 if (env.IsDevelopment()) 46 { 47 app.UseDeveloperExceptionPage(); 48 } 49 50 //启用中间件服务生成Swagger作为JSON终结点 51 app.UseSwagger(); 52 53 //启用中间件服务对swagger-ui,指定Swagger JSON终结点 54 app.UseSwaggerUI(c => 55 { 56 c.SwaggerEndpoint("/swagger/v1/swagger.json", "DemoAPI V1"); 57 //c.RoutePrefix = "swagger"; //默认 58 c.RoutePrefix = string.Empty; 59 }); 60 61 app.UseMvc(); 62 } 63 } 64 }
⒋添加 特性相关NuGet 包
1 Install-Package Swashbuckle.AspNetCore.Annotations
⒌修改Startup中的ConfigureServices方法,启用特性支持
1 public void ConfigureServices(IServiceCollection services) 2 { 3 services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); 4 5 //注册Swagger生成器,定义一个和多个Swagger 文档 6 services.AddSwaggerGen(option => 7 { 8 //配置第一个Doc 9 option.SwaggerDoc("v1", new Info 10 { 11 Version = "v1", 12 Title = "My API_1" 13 }); 14 //启用特性支持 15 option.EnableAnnotations(); 16 }); 17 }
⒍一些示范