public ISwaggerProvider GetSwaggerProvider(HttpRequestMessage swaggerRequest)
        {
            var httpConfig = swaggerRequest.GetConfiguration();

            var securityDefintitions = _securitySchemeBuilders.Any()
                ? _securitySchemeBuilders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Build())
                : null;

            // NOTE: Instantiate & add the XML comments filters here so they're executed before any
            // custom filters AND so they can share the same XPathDocument (perf. optimization)
            var modelFilters     = _modelFilters.Select(factory => factory()).ToList();
            var operationFilters = _operationFilters.Select(factory => factory()).ToList();

            foreach (var xmlDocFactory in _xmlDocFactories)
            {
                var xmlDoc = xmlDocFactory();
                modelFilters.Insert(0, new ApplyXmlTypeComments(xmlDoc));
                operationFilters.Insert(0, new ApplyXmlActionComments(xmlDoc));
            }

            foreach (var s in _securitySchemeBuilders.Where(x => x.Value.GetType() == typeof(ApiKeySchemeBuilder)))
            {
                var apiKeySch = (ApiKeySchemeBuilder)s.Value;
                operationFilters.Add(new ApplySwaggerOperationApiKey(apiKeySch.name, apiKeySch.type));
            }

            var options = new SwaggerGeneratorOptions(
                versionSupportResolver: _versionSupportResolver,
                schemes: _schemes,
                securityDefinitions: securityDefintitions,
                ignoreObsoleteActions: _ignoreObsoleteActions,
                accessControlAllowOrigin: _accessControlAllowOrigin,
                groupingKeySelector: _groupingKeySelector,
                groupingKeyComparer: _groupingKeyComparer,
                customSchemaMappings: _customSchemaMappings,
                schemaFilters: _schemaFilters.Select(factory => factory()).ToList(),
                modelFilters: modelFilters,
                ignoreObsoleteProperties: _ignoreObsoleteProperties,
                schemaIdSelector: _schemaIdSelector,
                describeAllEnumsAsStrings: _describeAllEnumsAsStrings,
                describeStringEnumsInCamelCase: _describeStringEnumsInCamelCase,
                ignoreObsoleteEnumConstants: _ignoreObsoleteEnumConstants,
                applyFiltersToAllSchemas: _applyFiltersToAllSchemas,
                ignoreIsSpecifiedMembers: _ignoreIsSpecifiedMembers,
                operationFilters: operationFilters,
                documentFilters: _documentFilters.Select(factory => factory()).ToList(),
                conflictingActionsResolver: _conflictingActionsResolver,
                operationIdResolver: _operationIdResolver
                );

            var defaultProvider = new SwaggerGenerator(
                httpConfig.Services.GetApiExplorer(),
                httpConfig.SerializerSettingsOrDefault(),
                _versionInfoBuilder.Build(),
                options);

            return((_customProviderFactory != null)
                ? _customProviderFactory(defaultProvider)
                : defaultProvider);
        }
Esempio n. 2
0
        /// <summary>Generates a Swagger specification for the given controller types.</summary>
        /// <param name="controllerTypes">The types of the controller.</param>
        /// <returns>The <see cref="SwaggerDocument" />.</returns>
        /// <exception cref="InvalidOperationException">The operation has more than one body parameter.</exception>
        public async Task <SwaggerDocument> GenerateForControllersAsync(IEnumerable <Type> controllerTypes)
        {
            var document = await CreateDocumentAsync().ConfigureAwait(false);

            var schemaResolver = new SwaggerSchemaResolver(document, Settings);

            var usedControllerTypes = new List <Type>();

            foreach (var controllerType in controllerTypes)
            {
                var generator  = new SwaggerGenerator(_schemaGenerator, Settings, schemaResolver);
                var isIncluded = await GenerateForControllerAsync(document, controllerType, generator, schemaResolver).ConfigureAwait(false);

                if (isIncluded)
                {
                    usedControllerTypes.Add(controllerType);
                }
            }

            document.GenerateOperationIds();

            foreach (var processor in Settings.DocumentProcessors)
            {
                await processor.ProcessAsync(new DocumentProcessorContext(document, controllerTypes, usedControllerTypes, schemaResolver, _schemaGenerator, Settings));
            }

            return(document);
        }
        public static void Init(TestContext testContext)
        {
            var t = typeof(CompaniesController);

            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.EnsureInitialized();

            var apiExplorer = new ApiExplorer(config);
            var settings    = new JsonSerializerSettings();
            var versions    = new Dictionary <string, Info> {
                { "v1", new Info()
                  {
                      version = "v1", title = "Test API"
                  } }
            };
            var options = new SwaggerGeneratorOptions(operationFilters: new IOperationFilter[]
            {
                // default filters used by Swashbuckle
                new HandleFromUriParams(),
                new ApplySwaggerOperationAttributes(),
                new ApplySwaggerResponseAttributes(),
                new ApplySwaggerOperationFilterAttributes(),

                // our custom filters
                new AddAsObjectAnnotationOperationFilter(),
                new HandleGridViewDataSetReturnType()
            });
            var generator = new SwaggerGenerator(apiExplorer, settings, versions, options);

            document = generator.GetSwagger("http://localhost:61453/", "v1");
        }
Esempio n. 4
0
        public void It_should_honor_the_config_setting_to_ignore_obsolete_actions()
        {
            _config.IgnoreObsoleteActions = true;
            var swaggerSpec = new SwaggerGenerator(_config).ApiExplorerToSwaggerSpec(_apiExplorer);

            ApiSpec(swaggerSpec, "/Orders", "/api/orders", api => CollectionAssert.IsEmpty(api.Operations.Where(op => op.Nickname == "Orders_DeleteAll")));
        }
Esempio n. 5
0
        public void It_should_apply_all_configured_operation_spec_filters()
        {
            _config
            .PostFilter <AddStandardErrorCodes>()
            .PostFilter <AddAuthorizationErrorCodes>();

            var swaggerSpec = new SwaggerGenerator(_config).ApiExplorerToSwaggerSpec(_apiExplorer);

            OperationSpec(swaggerSpec, "/Orders", "/api/orders", 0, "POST", operation =>
                          Assert.AreEqual(2, operation.ResponseMessages.Count));

            OperationSpec(swaggerSpec, "/Orders", "/api/orders", 0, "GET", operation =>
                          Assert.AreEqual(2, operation.ResponseMessages.Count));

            OperationSpec(swaggerSpec, "/Orders", "/api/orders", 1, "GET", operation =>
                          Assert.AreEqual(2, operation.ResponseMessages.Count));

            OperationSpec(swaggerSpec, "/Orders", "/api/orders/{id}", 0, "DELETE", operation =>
                          Assert.AreEqual(2, operation.ResponseMessages.Count));

            OperationSpec(swaggerSpec, "/OrderItems", "/api/orders/{orderId}/items/{id}", 0, "GET", operation =>
                          Assert.AreEqual(2, operation.ResponseMessages.Count));

            OperationSpec(swaggerSpec, "/OrderItems", "/api/orders/{orderId}/items", 0, "GET", operation =>
                          Assert.AreEqual(2, operation.ResponseMessages.Count));

            OperationSpec(swaggerSpec, "/Customers", "/api/customers/{id}", 0, "GET", operation =>
                          Assert.AreEqual(3, operation.ResponseMessages.Count));

            OperationSpec(swaggerSpec, "/Customers", "/api/customers/{id}", 0, "DELETE", operation =>
                          Assert.AreEqual(3, operation.ResponseMessages.Count));
        }
Esempio n. 6
0
        public void It_should_generate_declarations_according_to_provided_strategy()
        {
            _config.GroupDeclarationsBy(apiDesc => apiDesc.ActionDescriptor.ControllerDescriptor.ControllerName);
            var swaggerSpec = new SwaggerGenerator(_config).ApiExplorerToSwaggerSpec(_apiExplorer);

            ApiDeclaration(swaggerSpec, "/Orders", dec =>
            {
                Assert.AreEqual("1.2", dec.SwaggerVersion);
                Assert.AreEqual("http://tempuri.org", dec.BasePath);
                Assert.AreEqual("/Orders", dec.ResourcePath);
            });

            ApiDeclaration(swaggerSpec, "/OrderItems", dec =>
            {
                Assert.AreEqual("1.2", dec.SwaggerVersion);
                Assert.AreEqual("http://tempuri.org", dec.BasePath);
                Assert.AreEqual("/OrderItems", dec.ResourcePath);
            });

            ApiDeclaration(swaggerSpec, "/Customers", dec =>
            {
                Assert.AreEqual("1.2", dec.SwaggerVersion);
                Assert.AreEqual("http://tempuri.org", dec.BasePath);
                Assert.AreEqual("/Customers", dec.ResourcePath);
            });
        }
Esempio n. 7
0
        public IActionResult GetSwDocByPath()
        {
            var document = SwaggerGenerator.GetSwagger("v1");
            var stream   = GeneratorWordDoc.Generator(document, out var memi, "Templates\\SwaggerDoc.cshtml");

            return(File(stream, memi, "api简化文档.doc"));
        }
Esempio n. 8
0
        public IActionResult GetSwDoc()
        {
            var document = SwaggerGenerator.GetSwagger("v1");
            var stream   = GeneratorWordDoc.Generator(document, out var memi);

            return(File(stream, memi, "api简化文档.doc"));
        }
Esempio n. 9
0
        public void It_should_generate_an_api_spec_for_each_url_in_a_declaration()
        {
            var swaggerSpec = new SwaggerGenerator(_config).ApiExplorerToSwaggerSpec(_apiExplorer);

            ApiDeclaration(swaggerSpec, "/Orders", dec =>
            {
                // 2: /api/orders, /api/orders/{id}
                Assert.AreEqual(2, dec.Apis.Count);

                ApiSpec(dec, "/api/orders", api => Assert.IsNull(api.Description));
                ApiSpec(dec, "/api/orders/{id}", api => Assert.IsNull(api.Description));
            });

            ApiDeclaration(swaggerSpec, "/OrderItems", dec =>
            {
                // 2: /api/orders/{orderId}/items/{id}, /api/orders/{orderId}/items?category={category}
                Assert.AreEqual(2, dec.Apis.Count);

                ApiSpec(dec, "/api/orders/{orderId}/items/{id}", api => Assert.IsNull(api.Description));
                ApiSpec(dec, "/api/orders/{orderId}/items", api => Assert.IsNull(api.Description));
            });

            ApiDeclaration(swaggerSpec, "/Customers", dec =>
            {
                // 2: /api/customers, /api/customers/{id}
                Assert.AreEqual(2, dec.Apis.Count);

                ApiSpec(dec, "/api/customers", api => Assert.IsNull(api.Description));
                ApiSpec(dec, "/api/customers/{id}", api => Assert.IsNull(api.Description));
            });
        }
        private bool RunOperationProcessors(SwaggerDocument document, MethodInfo methodInfo,
                                            SwaggerOperationDescription operationDescription, List <SwaggerOperationDescription> allOperations,
                                            SwaggerGenerator swaggerGenerator)
        {
            // 1. Run from settings
            foreach (var operationProcessor in Settings.OperationProcessors)
            {
                if (
                    operationProcessor.Process(new OperationProcessorContext(document, operationDescription, methodInfo,
                                                                             swaggerGenerator, allOperations), Settings) == false)
                {
                    return(false);
                }
            }

            // 2. Run from class attributes
            var operationProcessorAttribute = methodInfo.DeclaringType.GetTypeInfo()
                                              .GetCustomAttributes()
                                              // 3. Run from method attributes
                                              .Concat(methodInfo.GetCustomAttributes())
                                              .Where(a => a.GetType().Name == "SwaggerOperationProcessorAttribute");

            foreach (dynamic attribute in operationProcessorAttribute)
            {
                var operationProcessor = Activator.CreateInstance(attribute.Type);
                if (operationProcessor.Process(methodInfo, operationDescription, swaggerGenerator, allOperations) ==
                    false)
                {
                    return(false);
                }
            }

            return(true);
        }
Esempio n. 11
0
        private async Task <bool> GenerateForControllerAsync(SwaggerDocument document, Type controllerType,
                                                             IEnumerable <Tuple <ApiDescription, ControllerActionDescriptor> > controllerApiDescriptionGroup,
                                                             SwaggerGenerator swaggerGenerator, SwaggerSchemaResolver schemaResolver)
        {
            var hasIgnoreAttribute = controllerType.GetTypeInfo()
                                     .GetCustomAttributes()
                                     .Any(a => a.GetType().Name == "SwaggerIgnoreAttribute");

            if (hasIgnoreAttribute)
            {
                return(false);
            }

            var operations = new List <Tuple <SwaggerOperationDescription, ApiDescription, MethodInfo, IEnumerable <string>, IEnumerable <string> > >();

            foreach (var item in controllerApiDescriptionGroup)
            {
                var apiDescription = item.Item1;
                var method         = item.Item2.MethodInfo;

                var actionHasIgnoreAttribute = method.GetCustomAttributes().Any(a => a.GetType().Name == "SwaggerIgnoreAttribute");
                if (actionHasIgnoreAttribute)
                {
                    continue;
                }

                var path = apiDescription.RelativePath;
                if (!path.StartsWith("/", StringComparison.Ordinal))
                {
                    path = "/" + path;
                }

                var controllerActionDescriptor = (ControllerActionDescriptor)apiDescription.ActionDescriptor;
                var httpMethod = apiDescription.HttpMethod?.ToLowerInvariant() ?? SwaggerOperationMethod.Get;

                var operationDescription = new SwaggerOperationDescription
                {
                    Path      = path,
                    Method    = httpMethod,
                    Operation = new SwaggerOperation
                    {
                        IsDeprecated = method.GetCustomAttribute <ObsoleteAttribute>() != null,
                        OperationId  = GetOperationId(document, controllerActionDescriptor, method)
                    }
                };

                var consumes = apiDescription.SupportedRequestFormats
                               .Select(f => f.MediaType)
                               .Distinct();

                var produces = apiDescription.SupportedResponseTypes
                               .SelectMany(t => t.ApiResponseFormats.Select(f => f.MediaType))
                               .Distinct();

                operations.Add(new Tuple <SwaggerOperationDescription, ApiDescription, MethodInfo, IEnumerable <string>, IEnumerable <string> >(
                                   operationDescription, apiDescription, method, consumes, produces));
            }

            return(await AddOperationDescriptionsToDocumentAsync(document, controllerType, operations, swaggerGenerator, schemaResolver).ConfigureAwait(false));
        }
        public static void Init(TestContext testContext)
        {
            var options = new SwaggerGeneratorSettings();

            options.DocInclusionPredicate = (version, api) => true;
            options.OperationFilters.Add(new RemoveReadOnlyFromUriParametersOperationFilter());
            options.OperationFilters.Add(new RemoveBindNoneFromUriParametersOperationFilter());
            options.OperationFilters.Add(new AddAsObjectAnnotationOperationFilter());
            options.OperationFilters.Add(new HandleGridViewDataSetReturnType());
            options.SwaggerDocs.Add("v1", new Info()
            {
                Title = "Test API", Version = "v1"
            });

            var serviceCollection = new ServiceCollection()
                                    .AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>()
                                    .AddSingleton <IHostingEnvironment, HostingEnvironment>()
                                    .AddLogging();

            serviceCollection.AddMvc(setup => {
                setup.Conventions.Add(new ApiExplorerVisibilityEnabledConvention());
            })
            .AddApplicationPart(typeof(CompaniesController).Assembly);

            var serviceProvider = serviceCollection.BuildServiceProvider();

            var apiDescriptionGroupCollectionProvider = serviceProvider.GetService <IApiDescriptionGroupCollectionProvider>();

            var schemaRegistryFactory = new SchemaRegistryFactory(new JsonSerializerSettings(), new SchemaRegistrySettings());
            var generator             = new SwaggerGenerator(apiDescriptionGroupCollectionProvider, schemaRegistryFactory, options);

            document = generator.GetSwagger("v1");
        }
 public CachingSwaggerProvider(
     IOptions <SwaggerGeneratorOptions> optionsAccessor,
     IApiDescriptionGroupCollectionProvider apiDescriptionsProvider,
     ISchemaGenerator schemaGenerator,
     ICacheManager cacheManager)
 {
     _cacheManager     = cacheManager;
     _swaggerGenerator = new SwaggerGenerator(optionsAccessor.Value, apiDescriptionsProvider, schemaGenerator);
 }
Esempio n. 14
0
        public IActionResult Get(string id)
        {
            var definition = _repo.Get(id);
            var generator  = new SwaggerGenerator(definition);
            var jsonString = generator.Generate();

            //var jsonString = System.IO.File.ReadAllText("dynamic_swagger.json");
            var json = JsonConvert.DeserializeObject(jsonString);

            return(Json(json));
        }
        private async Task <bool> GenerateForControllerAsync(SwaggerDocument document, Type controllerType,
                                                             IEnumerable <Tuple <ApiDescription, ControllerActionDescriptor> > controllerApiDescriptionGroup,
                                                             SwaggerGenerator swaggerGenerator, SwaggerSchemaResolver schemaResolver)
        {
            var hasIgnoreAttribute = controllerType.GetTypeInfo()
                                     .GetCustomAttributes()
                                     .Any(a => a.GetType().Name == "SwaggerIgnoreAttribute");

            if (hasIgnoreAttribute)
            {
                return(false);
            }

            var operations = new List <Tuple <SwaggerOperationDescription, ApiDescription, MethodInfo> >();

            foreach (var item in controllerApiDescriptionGroup)
            {
                var apiDescription = item.Item1;
                var method         = item.Item2.MethodInfo;

                var actionHasIgnoreAttribute = method.GetCustomAttributes().Any(a => a.GetType().Name == "SwaggerIgnoreAttribute");
                if (actionHasIgnoreAttribute)
                {
                    continue;
                }

                var path = apiDescription.RelativePath;
                if (!path.StartsWith("/", StringComparison.Ordinal))
                {
                    path = "/" + path;
                }

                var controllerActionDescriptor = (ControllerActionDescriptor)apiDescription.ActionDescriptor;
                if (!Enum.TryParse <SwaggerOperationMethod>(apiDescription.HttpMethod, ignoreCase: true, result: out var swaggerOperationMethod))
                {
                    swaggerOperationMethod = SwaggerOperationMethod.Undefined;
                }

                var operationDescription = new SwaggerOperationDescription
                {
                    Path      = path,
                    Method    = swaggerOperationMethod,
                    Operation = new SwaggerOperation
                    {
                        IsDeprecated = method.GetCustomAttribute <ObsoleteAttribute>() != null,
                        OperationId  = GetOperationId(document, controllerActionDescriptor, method)
                    }
                };

                operations.Add(new Tuple <SwaggerOperationDescription, ApiDescription, MethodInfo>(operationDescription, apiDescription, method));
            }

            return(await AddOperationDescriptionsToDocumentAsync(document, controllerType, operations, swaggerGenerator, schemaResolver).ConfigureAwait(false));
        }
Esempio n. 16
0
        public static void Init(TestContext testContext)
        {
            var knownTypesOptions = Options.Create(new DotvvmApiOptions());

            knownTypesOptions.Value.AddKnownType(typeof(Company <string>));

            var options = new SwaggerGeneratorOptions
            {
                DocInclusionPredicate = (version, api) => true,
                OperationFilters      =
                {
                    new RemoveReadOnlyFromUriParametersOperationFilter(),
                    new RemoveBindNoneFromUriParametersOperationFilter(),
                    new AddAsObjectOperationFilter(knownTypesOptions)
                },
                DocumentFilters =
                {
                    new HandleKnownTypesDocumentFilter(knownTypesOptions)
                },
                SwaggerDocs =
                {
                    { "v1", new Info()
                        {
                            Title = "Test API", Version = "v1"
                        } }
                }
            };

            var serviceCollection = new ServiceCollection()
                                    .AddSingleton <ObjectPoolProvider, DefaultObjectPoolProvider>()
                                    .AddSingleton <IHostingEnvironment, HostingEnvironment>()
                                    .AddSingleton <DiagnosticSource>(p => new DiagnosticListener("test"))
                                    .AddLogging();

            serviceCollection.AddMvc(setup => setup.Conventions.Add(new ApiExplorerVisibilityEnabledConvention()))
            .AddApplicationPart(typeof(CompaniesController).Assembly);

            var serviceProvider = serviceCollection.BuildServiceProvider();
            var apiDescriptionGroupCollectionProvider = serviceProvider.GetRequiredService <IApiDescriptionGroupCollectionProvider>();

            var schemaSettings = new SchemaRegistryOptions()
            {
                SchemaFilters =
                {
                    new AddTypeToModelSchemaFilter()
                }
            };

            var schemaRegistryFactory = new SchemaRegistryFactory(new JsonSerializerSettings(), schemaSettings);
            var generator             = new SwaggerGenerator(apiDescriptionGroupCollectionProvider, schemaRegistryFactory, options);

            document = generator.GetSwagger("v1");
        }
 /// <summary>Initializes a new instance of the <see cref="AspNetCoreOperationProcessorContext" /> class.</summary>
 /// <param name="document">The document.</param>
 /// <param name="operationDescription">The operation description.</param>
 /// <param name="controllerType">Type of the controller.</param>
 /// <param name="methodInfo">The method information.</param>
 /// <param name="swaggerGenerator">The swagger generator.</param>
 /// <param name="schemaResolver">The schema resolver.</param>
 /// <param name="settings">The sett</param>
 /// <param name="allOperationDescriptions">All operation descriptions.</param>
 /// <param name="schemaGenerator">The schema generator.</param>
 public AspNetCoreOperationProcessorContext(
     SwaggerDocument document,
     SwaggerOperationDescription operationDescription,
     Type controllerType,
     MethodInfo methodInfo,
     SwaggerGenerator swaggerGenerator,
     JsonSchemaGenerator schemaGenerator,
     JsonSchemaResolver schemaResolver,
     SwaggerGeneratorSettings settings,
     IList <SwaggerOperationDescription> allOperationDescriptions)
     : base(document, operationDescription, controllerType, methodInfo, swaggerGenerator, schemaGenerator, schemaResolver, settings, allOperationDescriptions)
 {
 }
Esempio n. 18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DebuggingHandlerDocumentProvider"/> class.
 /// </summary>
 /// <param name="options">The <see cref="DebuggingOptions"/> used for configuration.</param>
 /// <param name="swaggerGenerator">The original <see cref="ISwaggerProvider"/> that provides documents for normal APIs.</param>
 /// <param name="documentGenerator">The <see cref="IDebuggingHandlerDocumentGenerator"/> used to generate documents for debugging handlers.</param>
 /// <param name="handlers">All implementations of <see cref="IDebuggingHandler"/>.</param>
 /// <param name="modifiers">All implementations of <see cref="ICanModifyDebugginHandlerDocument"/> that will be called to modify the document.</param>
 public DebuggingHandlerDocumentProvider(
     IOptions <DebuggingOptions> options,
     SwaggerGenerator swaggerGenerator,
     IDebuggingHandlerDocumentGenerator documentGenerator,
     IInstancesOf <IDebuggingHandler> handlers,
     IInstancesOf <ICanModifyDebugginHandlerDocument> modifiers)
 {
     _options           = options;
     _swaggerGenerator  = swaggerGenerator;
     _documentGenerator = documentGenerator;
     _handlers          = handlers;
     _modifiers         = modifiers;
 }
Esempio n. 19
0
 /// <summary>Initializes a new instance of the <see cref="OperationProcessorContext"/> class.</summary>
 /// <param name="document">The document.</param>
 /// <param name="operationDescription">The operation description.</param>
 /// <param name="methodInfo">The method information.</param>
 /// <param name="swaggerGenerator">The swagger generator.</param>
 /// <param name="allOperationDescriptions">All operation descriptions.</param>
 public OperationProcessorContext(
     SwaggerDocument document,
     SwaggerOperationDescription operationDescription,
     MethodInfo methodInfo,
     SwaggerGenerator swaggerGenerator,
     IList <SwaggerOperationDescription> allOperationDescriptions)
 {
     Document                 = document;
     OperationDescription     = operationDescription;
     MethodInfo               = methodInfo;
     SwaggerGenerator         = swaggerGenerator;
     AllOperationDescriptions = allOperationDescriptions;
 }
Esempio n. 20
0
        internal ISwaggerProvider GetSwaggerProvider(HttpRequestMessage swaggerRequest)
        {
            var httpConfig = swaggerRequest.GetConfiguration();

            var securityDefintitions = _securitySchemeBuilders.Any()
                ? _securitySchemeBuilders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Build())
                : null;

            var security = new List <IDictionary <string, IEnumerable <string> > >();

            foreach (var sec in _securityBuilders)
            {
                var tmpSec = new Dictionary <string, IEnumerable <string> > {
                    { sec, new List <string>()
                      {
                      } }
                };
                security.Add(tmpSec);
            }

            var options = new SwaggerGeneratorOptions(
                versionSupportResolver: _versionSupportResolver,
                schemes: _schemes,
                securityDefinitions: securityDefintitions,
                security: security,
                ignoreObsoleteActions: _ignoreObsoleteActions,
                groupingKeySelector: _groupingKeySelector,
                groupingKeyComparer: _groupingKeyComparer,
                customSchemaMappings: _customSchemaMappings,
                schemaFilters: _schemaFilters.Select(factory => factory()),
                modelFilters: _modelFilters.Select(factory => factory()),
                ignoreObsoleteProperties: _ignoreObsoleteProperties,
                schemaIdSelector: _schemaIdSelector,
                describeAllEnumsAsStrings: _describeAllEnumsAsStrings,
                describeStringEnumsInCamelCase: _describeStringEnumsInCamelCase,
                operationFilters: _operationFilters.Select(factory => factory()),
                documentFilters: _documentFilters.Select(factory => factory()),
                conflictingActionsResolver: _conflictingActionsResolver
                );

            var defaultProvider = new SwaggerGenerator(
                httpConfig.Services.GetApiExplorer(),
                httpConfig.SerializerSettingsOrDefault(),
                _versionInfoBuilder.Build(),
                options);

            return((_customProviderFactory != null)
                ? _customProviderFactory(defaultProvider)
                : defaultProvider);
        }
Esempio n. 21
0
        public SwaggerSpec SwaggerSpec()
        {
            lock (SyncRoot)
            {
                if (_swaggerSpec == null)
                {
                    var swaggerGenerator = new SwaggerGenerator();
                    var apiExplorer      = GlobalConfiguration.Configuration.Services.GetApiExplorer();
                    _swaggerSpec = swaggerGenerator.ApiExplorerToSwaggerSpec(apiExplorer);
                }
            }

            return(_swaggerSpec);
        }
Esempio n. 22
0
        public SchemasSwaggerGenerator(IHttpContextAccessor context, SwaggerOwinSettings swaggerSettings, IOptions <MyUrlsOptions> urlOptions)
        {
            this.context = context.HttpContext;

            this.urlOptions = urlOptions.Value;

            schemaGenerator = new SwaggerJsonSchemaGenerator(swaggerSettings);
            schemaResolver  = new SwaggerSchemaResolver(document, swaggerSettings);

            swaggerGenerator = new SwaggerGenerator(schemaGenerator, swaggerSettings, schemaResolver);

            schemaBodyDescription  = SwaggerHelper.LoadDocs("schemabody");
            schemaQueryDescription = SwaggerHelper.LoadDocs("schemaquery");
        }
        private async Task AddPrimitiveParameterAsync(
            string name, SwaggerOperation operation, ParameterInfo parameter, SwaggerGenerator swaggerGenerator)
        {
            var operationParameter = await swaggerGenerator.CreatePrimitiveParameterAsync(name, parameter).ConfigureAwait(false);

            operationParameter.Kind       = SwaggerParameterKind.Query;
            operationParameter.IsRequired = operationParameter.IsRequired || parameter.HasDefaultValue == false;

            if (parameter.HasDefaultValue)
            {
                operationParameter.Default = parameter.DefaultValue;
            }

            operation.Parameters.Add(operationParameter);
        }
Esempio n. 24
0
        public async Task <SwaggerDocument> Generate(IAppEntity app, IEnumerable <ISchemaEntity> schemas)
        {
            document = SwaggerHelper.CreateApiDocument(context, urlOptions, app.Name);

            schemaGenerator = new SwaggerJsonSchemaGenerator(settings);
            schemaResolver  = new SwaggerSchemaResolver(document, settings);

            swaggerGenerator = new SwaggerGenerator(schemaGenerator, settings, schemaResolver);

            GenerateSchemasOperations(schemas, app);

            await GenerateDefaultErrorsAsync();

            return(document);
        }
Esempio n. 25
0
        public void GetUniqueFriendlyId_Test()
        {
            var    apiDesc     = apiDescription("asdf", "POST");
            string friendlyId  = apiDesc.FriendlyId();
            string friendlyId2 = apiDesc.FriendlyId2();

            Assert.AreNotEqual(friendlyId, friendlyId2);

            var operationNames = new HashSet <string> {
                friendlyId, friendlyId2
            };
            var    swaggerGenerator = new SwaggerGenerator(null, null, null);
            string uniqueFriendlyId = swaggerGenerator.GetUniqueOperationId(apiDesc, operationNames);

            Assert.AreNotEqual(friendlyId2, uniqueFriendlyId);
        }
Esempio n. 26
0
        internal ISwaggerProvider GetSwaggerProvider(HttpRequestMessage swaggerRequest)
        {
            var httpConfig = swaggerRequest.GetConfiguration();

            var securityDefintitions = _securitySchemeBuilders.Any()
                ? _securitySchemeBuilders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.Build())
                : null;

            foreach (var xmlDocFactory in _xmlDocFactories)
            {
                var xmlDoc = xmlDocFactory();
                _operationFilters.Add(() => new ApplyXmlActionComments(xmlDoc));
                _modelFilters.Add(() => new ApplyXmlTypeComments(xmlDoc));
            }

            var options = new SwaggerGeneratorOptions(
                versionSupportResolver: _versionSupportResolver,
                schemes: _schemes,
                securityDefinitions: securityDefintitions,
                ignoreObsoleteActions: _ignoreObsoleteActions,
                groupingKeySelector: _groupingKeySelector,
                groupingKeyComparer: _groupingKeyComparer,
                customSchemaMappings: _customSchemaMappings,
                schemaFilters: _schemaFilters.Select(factory => factory()),
                modelFilters: _modelFilters.Select(factory => factory()),
                ignoreObsoleteProperties: _ignoreObsoleteProperties,
                schemaIdSelector: _schemaIdSelector,
                describeAllEnumsAsStrings: _describeAllEnumsAsStrings,
                describeStringEnumsInCamelCase: _describeStringEnumsInCamelCase,
                applyFiltersToAllSchemas: _applyFiltersToAllSchemas,
                operationFilters: _operationFilters.Select(factory => factory()),
                documentFilters: _documentFilters.Select(factory => factory()),
                conflictingActionsResolver: _conflictingActionsResolver
                );

            var defaultProvider = new SwaggerGenerator(
                httpConfig.Services.GetApiExplorer(),
                httpConfig.SerializerSettingsOrDefault(),
                _versionInfoBuilder.Build(),
                options);

            return((_customProviderFactory != null)
                ? _customProviderFactory(defaultProvider)
                : defaultProvider);
        }
        public void GetSwagger_SupportsOption_SchemaFilters()
        {
            var subject = new SwaggerGenerator(
                new SwaggerGeneratorOptions
            {
                SwaggerDocs = new Dictionary <string, OpenApiInfo>
                {
                    ["v1"] = new OpenApiInfo {
                        Version = "V1", Title = "Test API"
                    }
                }
            },
                new FakeApiDescriptionGroupCollectionProvider(new[]
            {
                ApiDescriptionFactory.Create <FakeController>(
                    c =>
                    nameof(c.ActionWithObjectParameter),
                    groupName: "v1",
                    httpMethod: "POST",
                    relativePath: "resource",
                    parameterDescriptions: new []
                {
                    new ApiParameterDescription
                    {
                        Name   = "param",
                        Source = BindingSource.Body
                    }
                })
            }),
                new SchemaGenerator(new SchemaGeneratorOptions
            {
                SchemaFilters = new List <ISchemaFilter>
                {
                    new VendorExtensionsSchemaFilter()
                }
            }, new SystemTextJsonBehavior(new JsonSerializerOptions()))
                );

            var document = subject.GetSwagger("v1");

            Assert.Equal(2, document.Components.Schemas["XmlAnnotatedType"].Extensions.Count);
            Assert.Equal("bar", ((OpenApiString)document.Components.Schemas["XmlAnnotatedType"].Extensions["X-foo"]).Value);
            Assert.Equal("v1", ((OpenApiString)document.Components.Schemas["XmlAnnotatedType"].Extensions["X-docName"]).Value);
        }
Esempio n. 28
0
        public void GenerateSimpleServiceYaml()
        {
            var generator = new SwaggerGenerator {
                Yaml = true, GeneratorName = "tests"
            };
            var fsdService = TestUtility.ParseTestApi(s_fsdText);
            var namedText  = generator.GenerateOutput(fsdService).NamedTexts.Single();

            namedText.Name.ShouldBe("TestApi.yaml");
            var jToken         = JToken.FromObject(new YamlDotNet.Serialization.DeserializerBuilder().Build().Deserialize(new StringReader(namedText.Text)));
            var jTokenExpected = JToken.FromObject(s_swaggerService, JsonSerializer.Create(SwaggerUtility.JsonSerializerSettings));

            JToken.DeepEquals(jToken, jTokenExpected).ShouldBe(true);

            var service = new SwaggerParser().ParseDefinition(namedText);

            service.Summary.ShouldBe("TestApi");
            service.Methods.Count.ShouldBe(fsdService.Methods.Count);
        }
Esempio n. 29
0
        /// <summary>
        ///  Generate swagger doc
        /// </summary>
        /// <param name="httpConfig"></param>
        public static void SaveSwaggerJsonDoc(this HttpConfiguration httpConfig)
        {
            var baseAddress = $"{Properties.Settings.Default.ServiceUrl}:{Properties.Settings.Default.ServicePort}/";

            // 1) Apply your WebApi config.
            //WebApiConfig.Register(httpConfig);
            httpConfig.EnsureInitialized();

            // 2) Generate in-memory swagger doc
            var swaggerProvider = new SwaggerGenerator(
                httpConfig.Services.GetApiExplorer(),
                httpConfig.Formatters.JsonFormatter.SerializerSettings,
                new Dictionary <string, Info> {
                { "v1", new Info {
                      version = "v1", title = "Push Notify"
                  } }
            },
                new SwaggerGeneratorOptions(
                    // apply your swagger options here ...
                    schemaIdSelector: (type) => type.FriendlyId(true),
                    conflictingActionsResolver: (apiDescriptions) => apiDescriptions.First()
                    )
                );
            var swaggerDoc = swaggerProvider.GetSwagger(baseAddress, "v1");

            // 3) Serialize
            var swaggerString = JsonConvert.SerializeObject(
                swaggerDoc,
                Formatting.Indented,
                new JsonSerializerSettings
            {
                NullValueHandling = NullValueHandling.Ignore,
                Converters        = new[] { new VendorExtensionsConverter() }
            }
                );

            if (!File.Exists(GetPath()))
            {
                File.Delete(GetPath());
            }

            File.WriteAllText(GetPath(), swaggerString);
        }
        public void GenerateSimpleServiceYaml()
        {
            var generator = new SwaggerGenerator {
                GeneratesJson = false, GeneratorName = "tests"
            };
            var fsdService = TestUtility.ParseTestApi(c_fsdText);
            var file       = generator.GenerateOutput(fsdService).Files.Single();

            file.Name.Should().Be("TestApi.yaml");
            var jToken         = JToken.FromObject(new DeserializerBuilder().Build().Deserialize(new StringReader(file.Text)));
            var jTokenExpected = JToken.FromObject(s_swaggerService, JsonSerializer.Create(SwaggerUtility.JsonSerializerSettings));

            JToken.DeepEquals(jToken, jTokenExpected).Should().BeTrue("{0} should be {1}", jToken, jTokenExpected);

            var service = new SwaggerParser().ParseDefinition(new ServiceDefinitionText(name: file.Name, text: file.Text));

            service.Summary.Should().Be("TestApi");
            service.Methods.Count.Should().Be(fsdService.Methods.Count);
        }
Esempio n. 31
0
 private void AddPrimitiveParameter(string name, SwaggerOperation operation, ParameterInfo parameter, SwaggerGenerator swaggerGenerator)
 {
     var operationParameter = swaggerGenerator.CreatePrimitiveParameter(name, parameter);
     operationParameter.Kind = SwaggerParameterKind.Query;
     operationParameter.IsRequired = operationParameter.IsRequired || parameter.HasDefaultValue == false;
     operation.Parameters.Add(operationParameter);
 }
Esempio n. 32
0
        private void AddPrimitiveParametersFromUri(string name, SwaggerOperation operation, ParameterInfo parameter, JsonObjectTypeDescription typeDescription, SwaggerGenerator swaggerGenerator)
        {
            if (typeDescription.Type.HasFlag(JsonObjectType.Array))
            {
                var operationParameter = swaggerGenerator.CreatePrimitiveParameter(name,
                    parameter.GetXmlDocumentation(), parameter.ParameterType.GetEnumerableItemType(), parameter.GetCustomAttributes().ToList());

                operationParameter.Kind = SwaggerParameterKind.Query;
                operationParameter.CollectionFormat = SwaggerParameterCollectionFormat.Multi;
                operation.Parameters.Add(operationParameter);
            }
            else
            {
                foreach (var property in parameter.ParameterType.GetRuntimeProperties())
                {
                    var attributes = property.GetCustomAttributes().ToList();
                    var fromQueryAttribute = attributes.SingleOrDefault(a => a.GetType().Name == "FromQueryAttribute");

                    var propertyName = TryGetStringPropertyValue(fromQueryAttribute, "Name") ?? JsonPathUtilities.GetPropertyName(property, _settings.DefaultPropertyNameHandling);
                    var operationParameter = swaggerGenerator.CreatePrimitiveParameter(propertyName, property.GetXmlSummary(), property.PropertyType, attributes);

                    // TODO: Check if required can be controlled with mechanisms other than RequiredAttribute

                    var parameterInfo = JsonObjectTypeDescription.FromType(property.PropertyType, attributes, _settings.DefaultEnumHandling);
                    var isFileArray = IsFileArray(property.PropertyType, parameterInfo);
                    if (parameterInfo.Type == JsonObjectType.File || isFileArray)
                        InitializeFileParameter(operationParameter, isFileArray);
                    else
                        operationParameter.Kind = SwaggerParameterKind.Query;

                    operation.Parameters.Add(operationParameter);
                }
            }
        }
Esempio n. 33
0
 private void AddBodyParameter(string name, ParameterInfo parameter, SwaggerOperation operation, SwaggerGenerator swaggerGenerator)
 {
     var operationParameter = swaggerGenerator.CreateBodyParameter(name, parameter);
     operation.Parameters.Add(operationParameter);
 }
Esempio n. 34
0
        private void AddFileParameter(ParameterInfo parameter, bool isFileArray, SwaggerOperation operation, SwaggerGenerator swaggerGenerator)
        {
            var attributes = parameter.GetCustomAttributes().ToList();

            // TODO: Check if there is a way to control the property name
            var operationParameter = swaggerGenerator.CreatePrimitiveParameter(parameter.Name, parameter.GetXmlDocumentation(), parameter.ParameterType, attributes);

            InitializeFileParameter(operationParameter, isFileArray);
            operation.Parameters.Add(operationParameter);
        }
Esempio n. 35
0
        private bool TryAddFileParameter(JsonObjectTypeDescription info, SwaggerOperation operation, ParameterInfo parameter, SwaggerGenerator swaggerGenerator)
        {
            var isFileArray = IsFileArray(parameter.ParameterType, info);
            if (info.Type == JsonObjectType.File || isFileArray)
            {
                AddFileParameter(parameter, isFileArray, operation, swaggerGenerator);
                return true;
            }

            return false;
        }