• 第10章Swagger自定义实现index.html页


    1 初始化index.html页

        复制原程序“index.html”页的内容到当前程序员“index.html”页。

        注意:是内容复制,如果是页面替换复制,则必须重新把“index.html”页的属性中的“生成操作”设定为:“嵌入的资源”。

    2 自定义SwaggerSetup依赖注入中间件

        using Common.GlobalVar;

    using Common.Helper;

    using log4net;

    using Microsoft.Extensions.DependencyInjection;

    using Microsoft.OpenApi.Models;

    using Swashbuckle.AspNetCore.Filters;

    using System.Runtime.InteropServices;

    using static Extensions.ServiceExtensions.CustomApiVersion;

    namespace Extensions.ServiceExtensions

    {

        ///

        /// Swagger依赖注入--类】

        ///

        ///

        /// 摘要:

        ///     通过AddSwaggerGen依赖注入中间,获取Api控制器方法的版本控制信息和注释等数据信息,依赖注入.Net7框架的内置容器中,为在“index.html”页面上渲染显示这些信息,作好预处理操作。

        ///

        public static class SwaggerSetup

        {

            #region 变量--私有/保护----静态

            ///

            /// 【日志】

            ///

            /// 摘要:

            ///     通过“Log4net”日志中间件实例,把当前类的操作信息持久化;或显显示在控制台窗口中。

            ///

            ///

            private static readonly ILog log = LogManager.GetLogger(typeof(SwaggerSetup));

            #endregion

            #region 方法--静态

            /// name="services">.Net(Core)框架内置依赖注入容器实例。

            ///

            /// 【添加SqlSugar注入】

            ///

            ///

            /// 摘要:

            ///     通过AddSwaggerGen依赖注入中间,获取Api控制器方法的版本控制信息和注释等数据信息,依赖注入.Net7框架的内置容器中,为在“index.html”页面上渲染显示这些信息,作好预处理操作。

            ///

            public static void AddSwaggerSetup(this IServiceCollection services)

            {

                if (services == null) throw new ArgumentNullException(nameof(services));

                var basePath = AppContext.BaseDirectory;

                //var basePath2 = Microsoft.DotNet.PlatformAbstractions.ApplicationEnvironment.ApplicationBasePath;

                var ApiName = AppSettings.app(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 = $"{ApiName} HTTP API " + version,

                            Contact = new OpenApiContact { Name = ApiName, Email = "Blog.Core@xxx.com", Url = new Uri("https://neters.club") },

                            License = new OpenApiLicense { Name = ApiName + " 官方文档", Url = new Uri("http://apk.neters.club/.doc/") }

                        });

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

                    });

                    c.UseInlineDefinitionsForEnums();

                    try

                    {

                        //这个就是刚刚配置的xml文件名

                        var xmlPath = Path.Combine(basePath, "WebApi.xml");

                        //默认的第二个参数是false,这个是controller的注释,记得修改

                        c.IncludeXmlComments(xmlPath, true);

                        //这个就是Model层的xml文件名

                        var xmlModelPath = Path.Combine(basePath, "Blog.Core.Model.xml");

                        c.IncludeXmlComments(xmlModelPath);

                    }

                    catch (Exception ex)

                    {

                        log.Error("WebApi.xmlBlog.Core.Model.xml 丢失,请检查并拷贝。\n" + ex.Message);

                    }

                    //Nuget--Swashbuckle.AspNetCore.Filters

                    // 开启加权小锁

                    c.OperationFilter<AddResponseHeadersFilter>();

                    c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

                    // header中添加token,传递到后台

                    c.OperationFilter<SecurityRequirementsOperationFilter>();

                    // ids4jwt切换

                    if (Permissions.IsUseIds4)

                    {

                        //接入identityserver4

                        c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme

                        {

                            Type = SecuritySchemeType.OAuth2,

                            Flows = new OpenApiOAuthFlows

                            {

                                Implicit = new OpenApiOAuthFlow

                                {

                                    AuthorizationUrl = new Uri($"{AppSettings.app(new string[] { "Startup", "IdentityServer4", "AuthorizationUrl" })}/connect/authorize"),

                                    Scopes = new Dictionary<string, string> {

                                    {

                                        "blog.core.api","ApiResource id"

                                    }

                                }

                                }

                            }

                        });

                    }

                    else

                    {

                        // Jwt Bearer 认证,必须是 oauth2

                        c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme

                        {

                            Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"",

                            Name = "Authorization",//jwt默认的参数名称

                            In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)

                            Type = SecuritySchemeType.ApiKey

                        });

                    }

                });

                //Nuget--Swashbuckle.AspNetCore.Newtonsoft

                services.AddSwaggerGenNewtonsoftSupport();

            }

            #endregion

        }

        ///

        /// 【自定义Api版本--类】

        ///

        /// 摘要:

        ///    该类中的枚举实例通过版本分类的方式,把当前程序中的Api控制器方法分为两类(也可以分为更多的类)

        /// 应用场景:

        ///     在由于前端版本迭代,而需要更新Api控制器方法时,为了兼容旧的前端就需要“Api版本控制在不修改旧的Api控制器方法,而是定义新的Api控制器方法,来解决前端版本迭代的兼容性问题。

        ///

        ///

        public class CustomApiVersion

        {

            ///

            /// Api版本--枚举】

            ///

            /// 摘要:

            ///    该枚举通过版本分类的方式,把当前程序中的Api控制器方法分为两类(也可以分为更多的类)

            /// 应用场景:

            ///     在由于前端版本迭代,而需要更新Api控制器方法时,为了兼容旧的前端就需要“Api版本控制在不修改旧的Api控制器方法,而是定义新的Api控制器方法,来解决前端版本迭代的兼容性问题。

            ///

            ///

            public enum ApiVersions

            {

                ///

                /// V1

                ///

                /// 摘要:

                ///    1种版本分类的Api控制器方法。

                ///

                ///

                V1 = 1,

               

                ///

                /// V2

                ///

                /// 摘要:

                ///    2种版本分类的Api控制器方法。

                ///

                ///

                V2 = 2,

            }

        }

    }

    3 重构Program类

    //通过AddSwaggerGen依赖注入中间,获取Api控制器方法的版本控制信息和注释等数据信息,依赖注入.Net7框架的内置容器中,为在“index.html”页面上渲染显示这些信息,作好预处理操作。

    builder.Services.AddSwaggerSetup();

    builder.Services.AddControllers();

        按F5执行程序,在执行登录操作后,即可跳转到自定义的“index.html”面,如上图所示

    对以上功能更为具体实现和注释见:221202_09Blog(Swagger自定义实现index.html页)。

     

  • 相关阅读:
    850. 矩形面积 II--(每日一难phase--day16)
    微原笔记基础
    【基于MAX78000的智能边缘应用设计大赛】
    系统优化与微服务架构、分布式架构的合理性思考
    辅助驾驶功能开发-功能对标篇(12)-NOA领航辅助系统-合众
    grpc 常用的几种通信模式
    QGIS展示三维DEM数据
    STM32CUBEIDE(11)----输出PWM及修改PWM频率与占空比
    Air001 TIM1高级定时器单脉冲输出模式使用
    TikTok+KOL:打造品牌种草的完美组合
  • 原文地址:https://blog.csdn.net/zhoujian_911/article/details/128151375