步骤一、
Nuget Packages安装,使用程序包管理器控制台,安装命令:Install-Package Swashbuckle.AspNetCore -Pre
步骤二、
在Startup 文件中添加配置:
public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //配置swagger services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Version = "v1", Title = " API 文档", Description = "by bj eland" }); //开启swagger认证 options.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "请输入带有Bearer的Token", Name = "Authorization", In = "header", Type = "apiKey" }); //Json Token认证方式,此方式为全局添加 options.AddSecurityRequirement(new Dictionary<string, IEnumerable<string>> { { "Bearer", Enumerable.Empty<string>() } }); }); //配置授权 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "JwtBearer"; options.DefaultChallengeScheme = "JwtBearer"; }).AddJwtBearer("JwtBearer", (jwtBearerOptions) => { jwtBearerOptions.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["JwtAudience:JwtSecurityKey"])),//秘钥 ValidateIssuer = true, ValidIssuer = Configuration["JwtAudience:Issuer"], ValidateAudience = true, ValidAudience = Configuration["JwtAudience:Audience"], ValidateLifetime = true, ClockSkew = TimeSpan.FromMinutes(5) }; }); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs"); c.DocumentTitle = "xx项目接口文档"; //页面API文档格式 Full=全部展开, List=只展开列表, None=都不展开 c.DocExpansion(DocExpansion.None); }); }