/// <summary>
        ///
        /// </summary>
        /// <param name="appBuilder"></param>
        /// <param name="swaggerConfigSection"></param>
        /// <param name="apiVersionDescriptionProvider"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseOpenApiSwashbuckleQi(this IApplicationBuilder appBuilder, IConfiguration configuration, IApiVersionDescriptionProvider apiVersionDescriptionProvider)
        {
            QiArg.NotNull(configuration, nameof(configuration));

            appBuilder.UseSwagger();

            #region Mapping Swagger config section
            var suaggerConfig       = configuration.GetSection(QiConfigurationSections.Swagger);
            var swaggerConfigValues = new SwaggerConfig();
            suaggerConfig.Bind(swaggerConfigValues);
            #endregion

            string swaggerOpenApiDocNamePrefix = $"{Assembly.GetExecutingAssembly().GetName().Name}".Replace(".", "") + "OpenAPISpecification";

            appBuilder.UseSwaggerUI(swaggerUiOptions =>
            {
                string swaggerJsonBasePath   = string.IsNullOrWhiteSpace(swaggerConfigValues.VirtualPath) ? string.Empty : $"/{swaggerConfigValues.VirtualPath}";
                swaggerUiOptions.RoutePrefix = string.Empty; //Allow swagger start when app run
                foreach (var description in apiVersionDescriptionProvider.ApiVersionDescriptions)
                {
                    swaggerUiOptions.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/" +
                                                     $"{swaggerOpenApiDocNamePrefix}{description.GroupName}/swagger.json",
                                                     description.GroupName.ToUpperInvariant());
                }


                swaggerUiOptions.DefaultModelExpandDepth(2);
                swaggerUiOptions.DefaultModelRendering(Swashbuckle.AspNetCore.SwaggerUI.ModelRendering.Model);
                swaggerUiOptions.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
            });


            return(appBuilder);
        }
        public WikiScraperService(HttpClient httpClient,
                                  ILogger <WikiScraperService> logger)
            : base(logger)
        {
            QiArg.NotNull(httpClient, nameof(httpClient));

            _httpClient = httpClient;
        }
        /// <summary>
        /// Adds an API explorer that is API version aware and Swagger implementation through Swashbuckle.
        /// </summary>
        /// <typeparam name="T">The type of any Class defined in the assembly which have the  'Request/Response' samples for Swagger.</typeparam>
        /// <param name="services">The <see cref="IServiceCollection">services</see> available in the application.</param>
        /// <param name="options">An <see cref="Action{T}">action</see> used to configure the provided options.</param>
        /// <returns>The original <paramref name="services"/> object.</returns>
        public static IServiceCollection AddVersioningAndOpenApiSwashbuckleQi <T>(this IServiceCollection services, ApiVersioningSwaggerOptionsQi options)
            where T : class

        {
            QiArg.NotNull(services, nameof(services));
            QiArg.NotNull(options, nameof(options));
            QiArg.NotNull(options.ApiAssembly, nameof(options.ApiAssembly));
            Contract.Ensures(Contract.Result <IServiceCollection>() != null);

            string swaggerOpenApiDocNamePrefix = $"{Assembly.GetExecutingAssembly().GetName().Name}".Replace(".", "") + "OpenAPISpecification";

            #region Versionning

            services.AddVersionedApiExplorer(setupAction =>
            {
                setupAction.GroupNameFormat = options.GroupNameFormat; /*This means, for OpenApi versioning , it will looks for a letter 'v',
                                                                        * followed by major and minor version. IE: v1, v1.0, v2, v2.0, etc...*/
            })
            .AddApiVersioning(setupAction => {
                setupAction.AssumeDefaultVersionWhenUnspecified = options.AssumeDefaultVersionWhenUnspecified;
                setupAction.DefaultApiVersion = options.DefaultApiVersion;
                setupAction.ReportApiVersions = options.ReportApiVersions;  //Send in the response the supported version
            });

            //Below line should be called after call "services.AddApiVersioning" else we'll end up with one version cause no other versions has been applied.
            var apiVersionDescriptionProvider = services.BuildServiceProvider().GetService <IApiVersionDescriptionProvider>();

            var title = options.ApiAssembly.GetCustomAttribute <AssemblyProductAttribute>()?.Product;

            var description = options.ApiAssembly.GetCustomAttribute <AssemblyDescriptionAttribute>()?.Description;

            #endregion

            #region Swagger

            //Handle the  swagger doc
            services.AddSwaggerGen(setupAction =>
            {
                setupAction.ExampleFilters();

                #region Header Request Examples


                if (options.HeaderSamplesKeyValues != null && options.HeaderSamplesKeyValues.Any())
                {
                    foreach (var item in options.HeaderSamplesKeyValues)
                    {
                        setupAction.OperationFilter <AddHeaderOperationFilter>(item.Key, item.Value);
                    }
                }


                #endregion



                foreach (var apiDescription in apiVersionDescriptionProvider.ApiVersionDescriptions)
                {
                    setupAction.SwaggerDoc(
                        $"{swaggerOpenApiDocNamePrefix}{apiDescription.GroupName}",
                        new OpenApiInfo()
                    {
                        Title          = $"{title} {apiDescription.ApiVersion}",
                        Version        = apiDescription.ApiVersion.ToString(),
                        Description    = apiDescription.IsDeprecated ? $"{description} - DEPRECATED" : description,
                        Contact        = options.SwaggerContactOpenApiInfo ?? null,
                        License        = options.SwaggerLicenseOpenApiInfo ?? null,
                        TermsOfService = options.SwaggerTermOfServiceOpenApiInfo ?? null
                    });
                }

                //To link Actions with the corresponding version of the OpenApi
                setupAction.DocInclusionPredicate((documentName, apiDescription) =>
                {
                    var actionApiVersionModel = apiDescription.ActionDescriptor.GetApiVersionModel(
                        ApiVersionMapping.Explicit   //This means , Action with the ApiVersion attribute
                        | ApiVersionMapping.Implicit //This means , Action with the default version

                        );

                    if (actionApiVersionModel == null)
                    {
                        return(true);
                    }

                    if (actionApiVersionModel.DeclaredApiVersions.Any())
                    {
                        return(actionApiVersionModel.DeclaredApiVersions.Any(v =>
                                                                             $"{swaggerOpenApiDocNamePrefix}v{v.ToString()}" == documentName));
                    }

                    return(actionApiVersionModel.ImplementedApiVersions.Any(v =>
                                                                            $"{swaggerOpenApiDocNamePrefix}v{v.ToString()}" == documentName));
                });

                //Custom schemaIds to avoid conflicts between types.
                setupAction.CustomSchemaIds(ctype => ctype.FullName);

                //getting the name of .Xml comments document.
                string xmlCommentsFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";

                //Get xml full path
                string xmlCommentsFullPath = Path.Combine(AppContext.BaseDirectory, xmlCommentsFile);

                //If exists the comment file we'll add it
                if (File.Exists(xmlCommentsFullPath))
                {
                    setupAction.IncludeXmlComments(xmlCommentsFullPath);
                }
            });

            //Specifying the assembly where goes the Swagger samples "Request / Response"
            services.AddSwaggerExamplesFromAssemblyOf <T>();
            #endregion

            return(services);
        }
Example #4
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="logger"></param>
 public QiHttpServiceBase(ILogger <QiHttpServiceBase> logger)
 {
     QiArg.NotNull(logger, nameof(logger));
     _logger = logger;
 }