1 引用NuGet 包:Swashbuckle.AspNetCore
2 在Startup里 使用以下方法
public void ConfigureServices(IServiceCollection services) { services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "XXX API", Version = "v1" }); var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);//获取应用程序所在目录(绝对,不受工作目录影响,建议采用此方法获取路径) var xmlPath = Path.Combine(basePath, "XXX.xml"); c.IncludeXmlComments(xmlPath); #region 启用swagger验证功能 var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } }, }; c.AddSecurityRequirement(security); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "JWT授权(数据将在请求头中进行传输) 在下方输入Bearer {token} 即可,注意两者之间有空格", Name = "Authorization",//jwt默认的参数名称 In = "header",//jwt默认存放Authorization信息的位置(请求头中) Type = "apiKey" }); #endregion }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseSwagger(); //启用中间件服务对swagger-ui,指定Swagger JSON终结点 app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "XXXX V1"); }); app.UseDeveloperExceptionPage(); } else { } app.UseAuthentication();//配置授权,否则会一直401 }
2 Visual Studio 右键相应的项目