什么是swagger
接口文档
.NET Core引入Swagger
1、 .netcore 3.1
2、安装包 Swashbuckle.AspNetCore
3、代码配置
public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
4、项目->属性->生成
5、启动访问
/swagger/index.html
Swagger配置
多版本控制
public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1", Description = "我是一个描述", TermsOfService = new Uri("https://www.cnblogs.com/wudequn"), Contact = new OpenApiContact { Name = "西伯利亚的狼", Email = "xxx@xxx.com", Url = new Uri("https://www.cnblogs.com/wudequn") }, License = new OpenApiLicense { Name = "西伯利亚的狼2020许可证", Url = new Uri("https://www.cnblogs.com/wudequn") } }); c.SwaggerDoc("v2", new OpenApiInfo { Title = "My API", Version = "v2", Description = "我是一个描述v2", TermsOfService = new Uri("https://www.cnblogs.com/wudequn"), Contact = new OpenApiContact { Name = "西伯利亚的狼v2", Email = "xxx@xxx.com", Url = new Uri("https://www.cnblogs.com/wudequn") }, License = new OpenApiLicense { Name = "西伯利亚的狼2020许可证v2", Url = new Uri("https://www.cnblogs.com/wudequn") } }); var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); services.AddControllers(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); c.SwaggerEndpoint("/swagger/v2/swagger.json", "My API V2"); }); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }