.net core WebApi 使用Swagger生成API文档

关于 Swagger

Swagger能成为最受欢迎的REST APIs文档生成工具之一,有以下几个原因:

  • Swagger 可以生成一个具有互动性的API控制台,开发者可以用来快速学习和尝试API。
  • Swagger 可以生成客户端SDK代码用于各种不同的平台上的实现。
  • Swagger 文件可以在许多不同的平台上从代码注释中自动生成。
  • Swagger 有一个强大的社区,里面有许多强悍的贡献者。

Swagger 文档提供了一个方法,使我们可以用指定的 JSON摘要来描述你的 API,包括了比如 names、order 等 API 信息。

1、安装Swashbuckle.AspNetCore

using Swashbuckle.AspNetCore.Swagger;

   public void ConfigureServices(IServiceCollection services)
        {

            //注册Swagger生成器,定义一个和多个Swagger 文档
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });//设置版本号,标题

                var xmlPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "SwaggerApi.xml");//为Swagger设置xml文档注释路径
                c.IncludeXmlComments(xmlPath);//只有设置了xmlm文档的路径生成的文档才会有注释
                c.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader参数
            });
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

2、启用中间件服务

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            //启用中间件服务生成Swagger作为JSON终结点
            app.UseSwagger();
            //启用中间件服务对swagger-ui,指定Swagger JSON终结点
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.RoutePrefix = string.Empty;
            });
            app.UseHttpsRedirection();
            app.UseMvc();
        }

 

  3、新建HttpHeaderOperation

 public void Apply(Operation operation, OperationFilterContext context)
        {
            if (operation.Parameters == null)
            {
                operation.Parameters = new List<IParameter>();
            }
            
            var actionAttrs = context.ApiDescription.ActionAttributes();

            var isAuthorized = actionAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));

            if (isAuthorized == false) //提供action都没有权限特性标记,检查控制器有没有
            {
                var controllerAttrs = context.ApiDescription.ControllerAttributes();

                isAuthorized = controllerAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));
            }

            var isAllowAnonymous = actionAttrs.Any(a => a.GetType() == typeof(AllowAnonymousAttribute));

            if (isAuthorized && isAllowAnonymous == false)
            {
                operation.Parameters.Add(new NonBodyParameter()
                {
                    Name = "Authorization",  //添加Authorization头部参数
                    In = "header",
                    Type = "string",
                    Required = false,
                    Description = "access token"
                });
            }
        }

        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
            throw new NotImplementedException();
        }

4、配置XML文档路径

 5、地址栏输入http://localhost:{port}/swagger/index.html

 

posted @ 2019-04-28 13:58  装饰的梦  阅读(191)  评论(0编辑  收藏  举报