步骤一、
Nuget Packages安装,使用程序包管理器控制台,安装命令:Install-Package Swashbuckle.AspNetCore -Pre
步骤二、
在Startup 文件中添加配置:
public void ConfigureServices(IServiceCollection services){services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);//配置swaggerservices.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);});}