Asp.net core WebApi 使用Swagger生成帮助页

      最近咱们团队一直进行.net core的转型,web开发向着先后端分离的技术架构演进,咱们后台主要是采用了asp.net core webapi来进行开发,开始每次调试以及与前端人员的沟通上都存在这效率低下的问题,一次在看微软asp.net core官方文档的时候,发现了swagger这个好东西。而后在实际的项目中引入了该技术。咱们开发人员测试本身写的api的过程大大获得了简化,前端人员也能够根据咱们提供的swagger help pages 本身进行一些前端代码的测试,大大提升了先后端的开发效率。下面我就拿我本身的真实上线项目来一步一步的讲解如何在asp.net core webapi中引入swagger。(也能够参照微软官方文档:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swagger) 前端

     1、引入swagger Nuget包git

         右键点击wepapi项目的依赖项,点击管理Nuget程序包,以下图:github

     

在打开的NuGet包程序管理界面,输入:Swashbuckle.AspNetCore 目前该程序包的版本为1.0.0,点击安装。web

安装完后,须要在项目中的Startup.cs文件中进行配置。json

   2、配置Swagger后端

    打开Startup.cs 文件,在ConfigureServices 方法中,添加以下代码:api

    

 services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "TwBusManagement接口文档",
                    Description = "RESTful API for TwBusManagement",
                    TermsOfService = "None",
                    Contact = new Contact { Name = "Alvin_Su", Email = "asdasdasd@outlook.com", Url = "" }
                });

                //Set the comments path for the swagger json and ui.
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath = Path.Combine(basePath, "twbusapi.xml");
                c.IncludeXmlComments(xmlPath);

              //  c.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader参数
            });

注意上段代码的最后三行,是咱们api描述文档xml的生成地址和文件名,须要在项目的属性中进行配置。以下图:浏览器

另外上图中,禁止显示警告中,添加1591 代码,能够过滤掉一些类名没有写注释的报警信息。架构

最后须要在Configure方法中,添加以下代码,注意下面的代码必须添加在  app.UseMvc() 前面:app

 // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "TwBusManagement API V1");
                c.ShowRequestHeaders();
            });

以上配置完后,就可使用Swagger生成的帮助页面了,运行项目后,在浏览器地址 加上后缀 /swagger就能够跳转到帮助页面:

固然咱们开发人员在开发项目的过程当中并不想每次都要手动输入地址才能跳转到帮助页面,这样太麻烦。咱们可借助visual studio 进行跳转,以下图:

打开 launchSettings.json 文件,把webapi项目的启动路径设置成 swagger。这样每次调试运行项目都会自动跳转到swagger帮助页面

      3、Swagger的一些高级用法

      Swagger很是强大,不单单是一些帮助页面信息,还能够进行api的调试。这样就能够不用借助第三方工具 如:postman,进行webapi的调试。swagger通过配置,还能够输入一些http头部信息,如权限认证信息等。下面就来说解如下具体的配置。

        首先咱们须要新建一个类 HttpHeaderOperation,让该类继承IOperationFilter 接口,该接口需引入命名空间:Swashbuckle.AspNetCore.SwaggerGen,实现接口方法Apply 代码以下:

     

 public class HttpHeaderOperation : IOperationFilter
    {
        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
                });
            }
        }
    }

   而后在 Startup.cs 中的 ConfigureServices 方法,找到以前的AddSwaggerGen 代码段,在最后添加以下代码:

c.OperationFilter<HttpHeaderOperation>()
  services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version = "v1",
                    Title = "TwBusManagement接口文档",
                    Description = "RESTful API for TwBusManagement",
                    TermsOfService = "None",
                    Contact = new Contact { Name = "Alvin_Su", Email = "alvin_su@outlook.com", Url = "" }
                });

                //Set the comments path for the swagger json and ui.
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath = Path.Combine(basePath, "twbusapi.xml");
                c.IncludeXmlComments(xmlPath);

                c.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader参数
            });

 这样,咱们容许webapi项目后,就能够输入 Authorization 头部参数了。以下图:

 
 

   

 

        更多关于Swagger的用法能够参考https://github.com/domaindrivendev/Swashbuckle.AspNetCore 以及微软文档:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/web-api-help-pages-using-swagger

相关文章
相关标签/搜索