Swagger的使用

是一个API说明文档 .Net5已经内置

使用步骤

1. 安装Nuget包 Swashbuckle.AspNetCore Swashbuckle.AspNetCore.Filters
2. 简化Startup代码 我们直接新建一个类 来设置这个组件 代码如下
    /// <summary>
    /// 设置 SwaggerUI 组件
    /// </summary>
    public static class SwaggerSetup
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Filters.GlobalExceptionFilter));
        public static void AddSwaggerSetup(this IServiceCollection services, string basePath, string webApiXml, string ModelXml)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            var ApiName = Tools.Appsettings.GetSettingNode(new string[] { "Startup", "ApiName" });
            services.AddSwaggerGen(c =>
            {
                //遍历出全部的版本,做文档信息展示
                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    c.SwaggerDoc(version, new OpenApiInfo
                    {
                        Version = version,
                        Title = $"{ApiName} 接口文档——{RuntimeInformation.FrameworkDescription}",
                        Description = $"接口说明 " + version,
                        Contact = new OpenApiContact { Name = ApiName, Email = "", Url = new Uri("http://test2.myProject.com/") },

                    });
                    c.OrderActionsBy(o => o.RelativePath);
                });

                try
                {
                    // 为 Swagger JSON and UI设置xml文档注释路径
                    var xmlPath = Path.Combine(basePath, webApiXml);//"HC.NewSystem.WebApi.xml"
                    c.IncludeXmlComments(xmlPath, true);
                    var xmlModelPath = Path.Combine(basePath, ModelXml); // "HC.Core.DTO.Models.xml"   Model实体注释                  
                    c.IncludeXmlComments(xmlModelPath);
                }
                catch (Exception ex)
                {
                    log.Error("swagger UI所需 xml 文件不存在,请检查\n" + ex.Message);
                }

                // 开启加权小锁
                c.OperationFilter<AddResponseHeadersFilter>();
                c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();
                // 在header中添加token,传递到后台
                c.OperationFilter<SecurityRequirementsOperationFilter>();

                // Jwt Bearer 认证,必须是 oauth2
                c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "请直接在下框中输入请求头中需要添加的授权:Bearer {token}(注意两者之间是一个空格)\"",
                    Name = "Authorization",//jwt默认的参数名称
                    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                    Type = SecuritySchemeType.ApiKey            
                });

            });
           
        }
    }

接着在startup的Configservice中进行服务注册

  // Swagger UI
  services.AddSwaggerSetup(basePath, "HC.NewSystem.WebApi.xml", "HC.Product.DTO.Models.xml");//传入相应参数

接着我们对中间件进行一些扩展 对展示等进行自定义设置


    /// <summary>
    /// 中间件扩展(针对webpai中的swagger)
    /// </summary>
    public static class ApiSwaggerMildd
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(ApiSwaggerMildd));

        public static void UseSwaggerMildd(this IApplicationBuilder app, Func<Stream> streamHtml)
        {
            if (app == null) throw new ArgumentNullException(nameof(app));
            var Enaled = Appsettings.GetSettingNode(new string[] { "Startup", "Swagger", "Enaled" }).ObjToBool();
            var VirtualPath = Appsettings.GetSettingNode(new string[] { "Startup", "Swagger", "VirtualPath" });
            if (Enaled && string.IsNullOrEmpty(VirtualPath))
                throw new Exception("虚拟路径不存在,请进行相关配置!");

            app.UseSwagger(c =>
            {
                //c.PreSerializeFilters.Add((a, b) => a.BasePath = new Microsoft.OpenApi.Models.OpenApiPaths() {  });     
                if (Enaled)
                {
                    c.RouteTemplate = $"/{VirtualPath}/swagger/{{documentName}}/swagger.json";
                    c.PreSerializeFilters.Add((doc, httpReq) =>
                    {
                        doc.Servers = new List<OpenApiServer> { new OpenApiServer {
                        Url = $"/{VirtualPath}"
                        //Url=$"{httpReq.Scheme}://{httpReq.Host.Value}/{VirtualPath}/"
                    }};
                    });
                }

            });

            app.UseSwaggerUI(c =>
            {
                //根据版本名称倒序 遍历展示
                var ApiName = Appsettings.GetSettingNode(new string[] { "Startup", "ApiName" });
                //c.SwaggerEndpoint("/swagger/v1/swagger.json", "HC.Core.NewSystem v1");

                if (Enaled)
                {
                    typeof(ApiVersions).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version =>
                    {
                        c.SwaggerEndpoint($"{VirtualPath}/swagger/{version}/swagger.json", $"{ApiName} {version}");
                    });
                }
                else
                {
                    typeof(ApiVersions).GetEnumNames().OrderByDescending(e => e).ToList().ForEach(version =>
                    {
                        c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{ApiName} {version}");
                    });
                }

                // 将swagger首页,设置成我们自定义的页面,记得这个字符串的写法:{项目名.index.html}
                if (streamHtml.Invoke() == null)
                {
                    var msg = "index.html的属性,必须设置为嵌入的资源";
                    log.Error(msg);
                    throw new Exception(msg);
                }
                c.IndexStream = streamHtml;
                c.RoutePrefix = "";
                // 路径配置,设置为空,表示直接在根域名(localhost:8001)访问该文件,注意localhost:8001/swagger是访问不到的,去launchSettings.json把launchUrl去掉,如果你想换一个路径,直接写名字即可,比如直接写c.RoutePrefix = "doc";
                //if (Enaled)
                //    c.RoutePrefix = $"{VirtualPath}/";
                //else
                //    
            });
        }


    }

    /// <summary>
    /// API 自定义版本
    /// </summary>
    public enum ApiVersions
    {
        v1 = 1
    }

然后在 Configure中启用服务

      // Swagger
            app.UseSwaggerMildd(() => GetType().GetTypeInfo().Assembly.GetManifestResourceStream("HC.Product.WebApi.index.html"));

就可以了

posted @ 2021-02-19 18:00  C余L小R鱼  阅读(430)  评论(0编辑  收藏  举报