Asp.Net Core2.0 WebAPI 使用Swagger生成漂亮的…

2018-06-22 07:55:40来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

1、引用NuGet:

     Swashbuckle.AspNetCore.Swagger

     Swashbuckle.AspNetCore.SwaggerGen

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

2、Startup文件引用Swagger

 1 services.AddSwaggerGen(options =>
 2 {
 3     options.SwaggerDoc("v1", new Info
 4     {
 5         Version = "v1",
 6         Title = "WebApi文档"
 7     });
 8     options.OperationFilter<ApiHttpHeaderFilter>();
 9 
10     //Determine base path for the application.  
11     var basePath = PlatformServices.Default.Application.ApplicationBasePath;
12     //Set the comments path for the swagger json and ui.  
13     var xmlPath = Path.Combine(basePath, "WebApi.xml");
14     options.IncludeXmlComments(xmlPath);
15 });
1  app.UseSwagger();
2  app.UseSwaggerUI(c =>
3  {
4      c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebApi文档");
5  });

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

 1 using Microsoft.AspNetCore.Authorization;
 2 using Swashbuckle.AspNetCore.Swagger;
 3 using Swashbuckle.AspNetCore.SwaggerGen;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 
 7 namespace Core.WebApi.Filters
 8 {
 9     /// <summary>
10     /// 对需要进行授权登录的接口生成对应的文档输入框,如Bearer Token
11     /// </summary>
12     public class ApiHttpHeaderFilter : IDocumentFilter, IOperationFilter
13     {
14         /// <summary>
15         /// 
16         /// </summary>
17         /// <param name="operation"></param>
18         /// <param name="context"></param>
19         public void Apply(Operation operation, OperationFilterContext context)
20         {
21             operation.Parameters = operation.Parameters ?? new List<IParameter>();
22             var actionAttributes = context.ApiDescription.ActionAttributes();
23             var allowAnonymous = actionAttributes.Any(a => a.GetType() == typeof(AllowAnonymousAttribute)); // 查询是否过滤权限
24             if (!allowAnonymous)
25             {
26                 operation.Parameters.Add(new BodyParameter
27                 {
28                     Name = "Authorization",
29                     @In = "header",
30                     Description = "access token",
31                     Required = true
32                 });
33             }
34         }
35 
36         /// <summary>
37         /// 
38         /// </summary>
39         /// <param name="swaggerDoc"></param>
40         /// <param name="context"></param>
41         public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
42         {
43             throw new System.NotImplementedException();
44         }
45     }
46 }

   引用该类:

options.OperationFilter<ApiHttpHeaderFilter>();

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

  

 

效果:

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:定时器--Quartz.Net

下一篇:.NET使用DAO.NET实体类模型操作数据库