public void Process(DocumentProcessorContext context)
        {
            var operations = context.Document.Operations.ToList();

            foreach (var op in operations)
            {
                var operation = op.Operation;
                operation.Parameters.Add(new OpenApiParameter
                {
                    Name        = "LoginId",
                    IsRequired  = true,
                    Default     = LoginId,
                    Kind        = OpenApiParameterKind.Header,
                    Type        = JsonObjectType.String,
                    Description = "Login Id"
                });

                operation.Parameters.Add(new OpenApiParameter
                {
                    Name        = "AccountId",
                    IsRequired  = false,
                    Default     = AccountId,
                    Kind        = OpenApiParameterKind.Header,
                    Type        = JsonObjectType.String,
                    Description = "Account Id"
                });

                //foreach (var pa in operation.Parameters)
                //{
                //    pa.Name = Regex.Replace(pa.Name, @"^\w*\.", "");
                //}
            }
        }
        public async Task <SwaggerDocument> Generate(HttpContext httpContext, IAppEntity app, IEnumerable <ISchemaEntity> schemas)
        {
            document = NSwagHelper.CreateApiDocument(httpContext, urlOptions, app.Name);

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

            GenerateSchemasOperations(schemas, app);

            await GenerateDefaultErrorsAsync();

            var context =
                new DocumentProcessorContext(document,
                                             Enumerable.Empty <Type>(),
                                             Enumerable.Empty <Type>(),
                                             schemaResolver,
                                             schemaGenerator,
                                             settings);

            foreach (var processor in settings.DocumentProcessors)
            {
                await processor.ProcessAsync(context);
            }

            return(document);
        }
        public void Process(DocumentProcessorContext context)
        {
            if (!_openApiOptions.QueriesApi.AlterPathSchema)
            {
                return;
            }

            if (context.Document.Definitions.TryGetValue("ContentItemDto", out var contentItemDtoSchema))
            {
                var itemSchema = new JsonSchema
                {
                    Type          = JsonObjectType.Array,
                    IsNullableRaw = true,
                    Item          = new JsonSchema
                    {
                        Type      = JsonObjectType.Object,
                        Reference = contentItemDtoSchema
                    }
                };

                // TODO This only works when returning content items.
                // Consider a different path for documents?
                context.Document.Definitions["QueriesItemsDto"] = itemSchema;

                context.AlterPathSchema("/api/queries/{name}", "post", "200", itemSchema, (operation) =>
                {
                    operation.OperationId = _openApiOptions.QueriesApi.PostOperationId;
                });
                context.AlterPathSchema("/api/queries/{name}", "get", "200", itemSchema, (operation) =>
                {
                    operation.OperationId = _openApiOptions.QueriesApi.GetOperationId;
                });
            }
        }
Example #4
0
        public void Process(DocumentProcessorContext context)
        {
            foreach (var controllerType in context.ControllerTypes)
            {
                var tagAttribute = controllerType.GetTypeInfo().GetCustomAttribute <SwaggerTagAttribute>();

                if (tagAttribute != null)
                {
                    var tag = context.Document.Tags.Find(x => x.Name == tagAttribute.Name);

                    if (tag != null)
                    {
                        var description = controllerType.GetXmlSummaryAsync().Result;

                        if (description != null)
                        {
                            tag.Description = tag.Description ?? string.Empty;

                            if (!tag.Description.Contains(description))
                            {
                                tag.Description += "\n\n" + description;
                            }
                        }
                    }
                }
            }
        }
Example #5
0
        public async Task ProcessAsync(DocumentProcessorContext context)
        {
            var operationsToRemove = new List <string>();
            var operationsToAdd    = new Dictionary <string, SwaggerOperations>();

            foreach (var operation in context.Document.Paths)
            {
                if (!operation.Key.Contains(UrlTypeParameter))
                {
                    continue;
                }
                operationsToRemove.Add(operation.Key);
                foreach (var type in AnimalTypeMapper.Maps)
                {
                    var path          = operation.Key.Replace(UrlTypeParameter, type.Key);
                    var newOperations = new SwaggerOperations();
                    foreach (var response in operation.Value)
                    {
                        newOperations.Add(response.Key, await OperationBuilder.BuildOperationAsync(type.Key, response.Value, TypeParameter));
                    }
                    operationsToAdd.Add(path, newOperations);
                }
            }
            foreach (var remove in operationsToRemove)
            {
                context.Document.Paths.Remove(remove);
            }
            foreach (var newOperation in operationsToAdd)
            {
                context.Document.Paths.Add(newOperation.Key, newOperation.Value);
            }
        }
        public void Process(DocumentProcessorContext context)
        {
            foreach (var controllerType in context.ControllerTypes)
            {
                var attribute = controllerType.GetCustomAttribute <ApiExplorerSettingsAttribute>();

                if (attribute != null)
                {
                    var tag = context.Document.Tags.FirstOrDefault(x => x.Name == attribute.GroupName);

                    if (tag != null)
                    {
                        var description = controllerType.GetXmlDocsSummary();

                        if (description != null)
                        {
                            tag.Description ??= string.Empty;

                            if (!tag.Description.Contains(description))
                            {
                                tag.Description += "\n\n" + description;
                            }
                        }
                    }
                }
            }
        }
Example #7
0
        public Task ProcessAsync(DocumentProcessorContext context)
        {
            foreach (var controllerType in context.ControllerTypes)
            {
                var attribute = controllerType.GetTypeInfo().GetCustomAttribute <ApiExplorerSettingsAttribute>();

                if (attribute != null)
                {
                    var tag = context.Document.Tags.FirstOrDefault(x => x.Name == attribute.GroupName);

                    if (tag != null)
                    {
                        var description = controllerType.GetXmlSummaryAsync().Result;

                        if (description != null)
                        {
                            tag.Description = tag.Description ?? string.Empty;

                            if (!tag.Description.Contains(description))
                            {
                                tag.Description += "\n\n" + description;
                            }
                        }
                    }
                }
            }

            return(TaskHelper.Done);
        }
        public void Process(DocumentProcessorContext context)
        {
            foreach (var(_, operation) in context.Document.Paths.SelectMany(x => x.Value))
            {
                for (var i = 0; i < operation.Parameters.Count; i++)
                {
                    var operationParameter = operation.Parameters[i];
                    if (operationParameter.Type == NJsonSchema.JsonObjectType.File)
                    {
                        operation.Parameters.RemoveAt(i);
                        i--;
                        if (operation.RequestBody == null)
                        {
                            operation.RequestBody = new NSwag.OpenApiRequestBody();
                            var content = new NSwag.OpenApiMediaType();
                            operation.RequestBody.Content.Add("multipart/form-data", content);
                            content.Schema = new NJsonSchema.JsonSchema()
                            {
                                Type = NJsonSchema.JsonObjectType.Object,
                            };
                        }
                        var multipartFormData = operation.RequestBody.Content["multipart/form-data"];

                        multipartFormData.Schema.Properties.Add(operationParameter.Name, new NJsonSchema.JsonSchemaProperty()
                        {
                            Type   = NJsonSchema.JsonObjectType.String,
                            Format = "binary",
                        });
                    }
                }
            }
        }
        public void Process(DocumentProcessorContext context)
        {
            var healthReportSchema = context.SchemaGenerator.Generate(typeof(HealthReport), context.SchemaResolver);

            var getHealthOperation = new OpenApiOperation
            {
                OperationId = "GetHealth",
                Produces    = new List <string> {
                    "application/json"
                },
                Summary = "Performs health checks",
                Tags    = new List <string> {
                    "General"
                },
            };

            getHealthOperation.Responses.Add(
                StatusCodes.Status200OK.ToString(CultureInfo.InvariantCulture),
                new OpenApiResponse {
                Description = "Application is running OK", Schema = healthReportSchema
            });

            getHealthOperation.Responses.Add(
                StatusCodes.Status503ServiceUnavailable.ToString(CultureInfo.InvariantCulture),
                new OpenApiResponse {
                Description = "At least one health check reported an issue", Schema = healthReportSchema
            });

            var healthPathItem = new OpenApiPathItem
            {
                { "GET", getHealthOperation },
            };

            context.Document.Paths.Add(HealthChecksResponseWriter.HealthChecksEndpoint, healthPathItem);
        }
Example #10
0
        public async Task ProcessAsync(DocumentProcessorContext context)
        {
            var schema = context.SchemaResolver.GetSchema(typeof(RuleAction), false);

            if (schema != null)
            {
                var discriminator = new OpenApiDiscriminator
                {
                    JsonInheritanceConverter = new JsonInheritanceConverter("actionType", typeof(RuleAction)),
                    PropertyName             = "actionType"
                };

                schema.DiscriminatorObject      = discriminator;
                schema.Properties["actionType"] = new JsonProperty
                {
                    Type       = JsonObjectType.String,
                    IsRequired = true
                };

                foreach (var derived in RuleElementRegistry.Actions)
                {
                    var derivedSchema = await context.SchemaGenerator.GenerateAsync(derived.Value.Type, context.SchemaResolver);

                    var oldName = context.Document.Definitions.FirstOrDefault(x => x.Value == derivedSchema).Key;

                    if (oldName != null)
                    {
                        context.Document.Definitions.Remove(oldName);
                        context.Document.Definitions.Add(derived.Key, derivedSchema);
                    }
                }

                RemoveFreezable(context, schema);
            }
        }
Example #11
0
        public OpenApiDocument Generate(HttpContext httpContext, IAppEntity app, IEnumerable <ISchemaEntity> schemas)
        {
            document = NSwagHelper.CreateApiDocument(httpContext, urlOptions, app.Name);

            schemaGenerator = new OpenApiSchemaGenerator(settings);
            schemaResolver  = new OpenApiSchemaResolver(document, settings);

            statusSchema = GenerateStatusSchema();

            GenerateSchemasOperations(schemas, app);

            var context =
                new DocumentProcessorContext(document,
                                             Enumerable.Empty <Type>(),
                                             Enumerable.Empty <Type>(),
                                             schemaResolver,
                                             schemaGenerator,
                                             settings);

            foreach (var processor in settings.DocumentProcessors)
            {
                processor.Process(context);
            }

            return(document);
        }
Example #12
0
        private static void AlterSchemaDefinition(DocumentProcessorContext context, string definitionName, string schemaNameExtension)
        {
            var definition = context.Document.Definitions[definitionName];

            // TODO post configure action here.
            context.Document.Definitions.Remove(definitionName);
            context.Document.Definitions[definitionName + schemaNameExtension] = definition;
        }
Example #13
0
 /// <summary>Processes the specified Swagger document.</summary>
 /// <param name="context"></param>
 public void Process(DocumentProcessorContext context)
 {
     foreach (var controllerType in context.ControllerTypes)
     {
         ProcessSwaggerTagsAttribute(context.Document, controllerType);
         ProcessSwaggerTagAttributes(context.Document, controllerType);
     }
 }
 public static void TryRemoveDefinition(this DocumentProcessorContext context, string key)
 {
     if (context.Document.Definitions.TryGetValue(key, out var value))
     {
         value.AllOf.Clear();
         context.Document.Definitions.Remove(key);
     }
 }
Example #15
0
 public void Process(DocumentProcessorContext context)
 {
     foreach (var registrations in this.registrations.Safe()
              .Where(r => !r.Route.IsNullOrEmpty()).GroupBy(r => r.Route))
     {
         AddPathItem(context.Document.Paths, registrations.DistinctBy(r => r.RequestMethod), context);
     }
 }
 /// <summary>Processes the specified Swagger document.</summary>
 /// <param name="context"></param>
 public void Process(DocumentProcessorContext context)
 {
     foreach (var controllerType in context.ControllerTypes)
     {
         ProcessSwaggerTagsAttribute(context.Document, controllerType);
         ProcessSwaggerTagAttributes(context.Document, controllerType);
     }
 }
        public void Process(DocumentProcessorContext context)
        {
            if (string.IsNullOrEmpty(_openApiOptions.TenantsApi.ApiTag))
            {
                return;
            }

            context.Document.Paths.AlterApiControllerTag("/api/tenants", _openApiOptions.TenantsApi.ApiTag);
        }
Example #18
0
        /// <summary>Processes the specified Swagger document.</summary>
        /// <param name="context"></param>
#pragma warning disable 1998
        public async Task ProcessAsync(DocumentProcessorContext context)
#pragma warning restore 1998
        {
            foreach (var controllerType in context.ControllerTypes)
            {
                ProcessSwaggerTagsAttribute(context.Document, controllerType);
                ProcessSwaggerTagAttributes(context.Document, controllerType);
            }
        }
Example #19
0
        public void Process(DocumentProcessorContext context)
        {
            context.Document.BasePath = Constants.ApiPrefix;

            context.Document.Info.ExtensionData = new Dictionary <string, object>
            {
                ["x-logo"] = new { url, backgroundColor = Background }
            };
        }
Example #20
0
        public void Process(DocumentProcessorContext context)
        {
            context.Document.Info.Version       = version;
            context.Document.Info.ExtensionData = new Dictionary <string, object>
            {
                ["x-logo"] = new { url = logoUrl, backgroundColor = logoBackground }
            };

            context.Document.ExternalDocumentation = documentation;
        }
Example #21
0
        public void Process(DocumentProcessorContext context)
        {
            if (string.IsNullOrEmpty(_openApiOptions.ContentsApi.ApiTag))
            {
                return;
            }

            // This alters the api/content path to a more useful path segment.
            context.Document.Paths.AlterApiControllerTag("/api/content", _openApiOptions.ContentsApi.ApiTag);
        }
Example #22
0
        public Task ProcessAsync(DocumentProcessorContext context)
        {
            context.Document.BasePath = Constants.ApiPrefix;

            context.Document.Info.ExtensionData = new Dictionary <string, object>
            {
                ["x-logo"] = new { url, backgroundColor = Background }
            };

            return(TaskHelper.Done);
        }
Example #23
0
        public async Task ProcessAsync(DocumentProcessorContext context)
        {
            var errorSchema = await GetErrorSchemaAsync(context);

            foreach (var operation in context.Document.Paths.Values.SelectMany(x => x.Values))
            {
                AddErrorResponses(operation, errorSchema);

                CleanupResponses(operation);
            }
        }
Example #24
0
 public void Process(DocumentProcessorContext context)
 {
     foreach (var pathToRemove in _openApiOptions.PathOptions.PathsToRemove)
     {
         var paths = context.Document.Paths.Where(x => x.Key.Contains(pathToRemove));
         foreach (var path in paths.Select(x => x.Key))
         {
             context.Document.Paths.Remove(path);
         }
     }
 }
Example #25
0
        public void Process(DocumentProcessorContext context)
        {
            var errorSchema = GetErrorSchema(context);

            foreach (var operation in context.Document.Paths.Values.SelectMany(x => x.Values))
            {
                AddErrorResponses(operation, errorSchema);

                CleanupResponses(operation);
            }
        }
Example #26
0
        private static void AddDefaultResponseSchemas(DocumentProcessorContext context)
        {
            if (!ResponseSchemas.ContainsKey(nameof(ProblemDetails)))
            {
                ResponseSchemas.Add(nameof(ProblemDetails), context.SchemaGenerator.Generate(typeof(ProblemDetails), context.SchemaResolver));
            }

            //if (!ResponseSchemas.ContainsKey(nameof(ValidationProblemDetails)))
            //{
            //    ResponseSchemas.Add(nameof(ValidationProblemDetails), context.SchemaGenerator.Generate(typeof(ValidationProblemDetails), context.SchemaResolver));
            //}
        }
Example #27
0
 public void Process(DocumentProcessorContext context)
 {
     foreach (var controllerType in context.ControllerTypes)
     {
         context.Document.Tags.Add(new NSwag.OpenApiTag
         {
             Name        = GetControllerName(controllerType),
             Description = controllerType.GetXmlDocsSummary()
                           //ExternalDocumentation=new NSwag.OpenApiExternalDocumentation { Url= "http://swagger.io", Description= "Find out more about our store" }
         });
     }
 }
Example #28
0
        public void Process(DocumentProcessorContext context)
        {
            if (!_openApiOptions.ContentsApi.RemoveContentElements)
            {
                return;
            }

            context.TryRemoveDefinition("ContentElement");
            context.TryRemoveDefinition("ContentItem");
            context.TryRemoveDefinition("ContentField");
            context.TryRemoveDefinition("ContentPart");
        }
        public void Process(DocumentProcessorContext context)
        {
            StringBuilder description = new StringBuilder();

            description.AppendLine("# Error Codes");
            description.AppendLine("name | value");
            description.AppendLine("---- | -----");
            foreach (var(name, value) in GetAllErrorCodes())
            {
                description.AppendLine($"`{name}` | `{value}`");
            }

            context.Document.Info.Description = description.ToString();
        }
Example #30
0
        public void Process(DocumentProcessorContext context)
        {
            context.Document.BasePath = "/api";

            var logo = new
            {
                url = "/logo.svg"
            };

            context.Document.Info.Version       = "1.0.0";
            context.Document.Info.ExtensionData = new Dictionary <string, object>
            {
                ["x-logo"] = logo
            };
        }
Example #31
0
        public void Process(DocumentProcessorContext context)
        {
            if (this.configuration?.Registrations == null)
            {
                return;
            }

            AddDefaultResponseSchemas(context);

            foreach (var registrations in this.configuration.Registrations
                     .Where(e => !e.Pattern.IsNullOrEmpty()).GroupBy(e => e.Pattern))
            {
                AddPathItem(context.Document.Paths, registrations.DistinctBy(r => r.Method), context);
            }
        }
Example #32
0
 /// <summary>Processes the specified Swagger document.</summary>
 /// <param name="context"></param>
 public void Process(DocumentProcessorContext context)
 {
     context.Document.SecurityDefinitions[_name] = _swaggerSecurityScheme;
 }