1、引用NuGet:

Swashbuckle.AspNetCore.Swagger

Swashbuckle.AspNetCore.SwaggerGen

Asp.Net Core2.0 WebAPI 使用Swagger生成漂亮的接口文档

或

<PackageReference Include="Swashbuckle.AspNetCore.Swagger" Version="1.1.0" />
  <PackageReference Include="Swashbuckle.AspNetCore.SwaggerGen" Version="1.1.0" />

2、Startup文件引用Swagger

services.AddSwaggerGen(options =>
 {
     options.SwaggerDoc("v1", new Info
     {
         Version = "v1",
         Title = "WebApi文档"
     });
     options.OperationFilter<ApiHttpHeaderFilter>();
 
     //Determine base path for the application.  
     var basePath = PlatformServices.Default.Application.ApplicationBasePath;
     //Set the comments path for the swagger json and ui.  
     var xmlPath = Path.Combine(basePath, "WebApi.xml");
     options.IncludeXmlComments(xmlPath);
 });
app.UseSwagger();
  app.UseSwaggerUI(c =>
  {
      c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApi文档");
  });

3、对需要进行授权登录的接口生成对应的文档输入框,如Bearer Token

using Microsoft.AspNetCore.Authorization;
 using Swashbuckle.AspNetCore.Swagger;
 using Swashbuckle.AspNetCore.SwaggerGen;
 using System.Collections.Generic;
 using System.Linq;
 
 namespace Core.WebApi.Filters
 {
     /// <summary>
     /// 对需要进行授权登录的接口生成对应的文档输入框,如Bearer Token
     /// </summary>
     public class ApiHttpHeaderFilter : IDocumentFilter, IOperationFilter
     {
         /// <summary>
         /// 
         /// </summary>
         /// <param name="operation"></param>
         /// <param name="context"></param>
         public void Apply(Operation operation, OperationFilterContext context)
         {
             operation.Parameters = operation.Parameters ?? new List<IParameter>();
             var actionAttributes = context.ApiDescription.ActionAttributes();
             var allowAnonymous = actionAttributes.Any(a => a.GetType() == typeof(AllowAnonymousAttribute)); // 查询是否过滤权限
             if (!allowAnonymous)
             {
                 operation.Parameters.Add(new BodyParameter
                 {
                     Name = "Authorization",
                     @In = "header",
                     Description = "access token",
                     Required = true
                 });
             }
         }
 
         /// <summary>
         /// 
         /// </summary>
         /// <param name="swaggerDoc"></param>
         /// <param name="context"></param>
         public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
         {
             throw new System.NotImplementedException();
         }
     }
 }

引用该类:

options.OperationFilter<ApiHttpHeaderFilter>();

4、点击项目右键属性(勾选生成WebApi.xml文档):

Asp.Net Core2.0 WebAPI 使用Swagger生成漂亮的接口文档

效果:

Asp.Net Core2.0 WebAPI 使用Swagger生成漂亮的接口文档