Package
添加并配置Swagger中间件
将Swagger生成器添加到方法中的服务集合中Startup.ConfigureServices
:
public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "WoorldCup Api", Version = "v1" }); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); }); }
在该Startup.Configure方法中,启用用于为生成的JSON文档和Swagger UI提供服务的中间件:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "WoorldCup Api V1"); }); app.UseMvc(); }
Controller标记
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using WorldCup.Data; namespace WorldCup.Controllers { /// <summary> /// 比赛相关 /// </summary> [Route("api/[controller]")] public class MatchController : Controller { private readonly WorldCupDBContext _worldCupDb; private readonly IHostingEnvironment _hostingEnvironment; public MatchController(WorldCupDBContext worldCupDb) { _worldCupDb = worldCupDb; } /// <summary> /// 获取所有队伍 /// </summary> /// <returns></returns> [HttpGet("GetAllTeam")] public IActionResult GetAllTeam(TodoItem item) { return Ok(new { Result = _worldCupDb.WorldCup_Country.ToList() }); } } public class TodoItem { public long Id { get; set; } [Required] public string Name { get; set; } [DefaultValue(false)] public bool IsComplete { get; set; } } }
效果
文档分组
services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "登录", Version = "v1" }); c.SwaggerDoc("v2", new Info { Title = "题目答案", Version = "v1" }); c.SwaggerDoc("v3", new Info { Title = "KPI", Version = "v1" }); var basePath = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath; var xmlPath = System.IO.Path.Combine(basePath, $"{nameof(CMBCampaign)}.xml"); c.IncludeXmlComments(xmlPath, true); //添加header验证信息 var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } } }; //添加一个必须的全局安全信息,和AddSecurityDefinition方法指定的方案名称要一直,这里是Bearer; c.AddSecurityRequirement(security); c.AddSecurityDefinition("Bearer", new ApiKeyScheme() { Description = "JWT授权(数据将在请求头中进行传输) 参数结构:"Authorization:Bearer {token}"", Name = SystemGlobalConst.Token,// jwt默认的参数名称 "Authorization",// In = "header",//jwt默认存放Authorization信息的位置(请求头中) Type = "apiKey" }); });
if (Configuration.GetSection("ShowSwagger").Value == "true") { app.UseSwagger().UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "登录"); c.SwaggerEndpoint("/swagger/v2/swagger.json", "题目答案"); c.SwaggerEndpoint("/swagger/v3/swagger.json", "KPI"); }); }
微软文档:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swagger?view=aspnetcore-2.1