public async Task Invoke(HttpContext httpContext)
        {
            var response = httpContext.Response;

            response.StatusCode  = 200;
            response.ContentType = "application/json;charset=utf-8";

            if (_documentJson == null)
            {
                var swaggerGen = httpContext.RequestServices
                                 .GetRequiredService <ISwaggerProvider>();
                _document = swaggerGen.GetSwagger(Info.Title.ToLower().Replace(' ', '_'));

                using var textWriter = new StringWriter(CultureInfo.InvariantCulture);
                var jsonWriter = new OpenApiJsonWriter(textWriter);
                if (_asV2)
                {
                    _document.SerializeAsV2(jsonWriter);
                }
                else
                {
                    _document.SerializeAsV3(jsonWriter);
                }

                _documentJson = textWriter.ToString();
            }

            await response.WriteAsync(_documentJson, new UTF8Encoding(false));
        }
        public void WriteStringListAsJsonShouldMatchExpected(string[] stringValues, bool produceTerseOutput)
        {
            // Arrange
            var outputString = new StringWriter(CultureInfo.InvariantCulture);
            var writer       = new OpenApiJsonWriter(outputString, new OpenApiJsonWriterSettings {
                Terse = produceTerseOutput
            });

            // Act
            writer.WriteStartArray();
            foreach (var stringValue in stringValues)
            {
                writer.WriteValue(stringValue);
            }

            writer.WriteEndArray();
            writer.Flush();

            var parsedObject   = JsonConvert.DeserializeObject(outputString.GetStringBuilder().ToString());
            var expectedObject =
                JsonConvert.DeserializeObject(JsonConvert.SerializeObject(new List <string>(stringValues)));

            // Assert
            parsedObject.Should().BeEquivalentTo(expectedObject);
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "swagger.json")] HttpRequest req,
            ILogger log)
        {
            var url = req.GetDisplayUrl();

            if (req.Path.HasValue && !string.IsNullOrWhiteSpace(req.Path.Value))
            {
                url = url.Replace(req.Path, string.Empty);
            }
            if (req.QueryString.HasValue && !string.IsNullOrWhiteSpace(req.QueryString.Value))
            {
                url = url.Replace(req.QueryString.Value, string.Empty);
            }
            var host            = new WebHostBuilder().UseStartup <Startup>().Build();
            var swaggerProvider = host.Services.GetRequiredService <ISwaggerProvider>();
            var swagger         = swaggerProvider.GetSwagger("v1");

            swagger.Servers.Add(new OpenApiServer {
                Url = url
            });

            using (var writer = new StringWriter(new StringBuilder()))
            {
                var jsonWriter = new OpenApiJsonWriter(writer);
                //swagger.SerializeAsV3(jsonWriter);
                swagger.SerializeAsV2(jsonWriter);
                var obj = JObject.Parse(writer.ToString());
                return(new JsonResult(obj));
            }
        }
Exemplo n.º 4
0
        public IActionResult Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = SwaggerJsonRoute)] HttpRequest req)
        {
            try
            {
                var document = _swaggerProvider.GetSwagger(_info.Version);
                using (var stringWriter = new StringWriter(CultureInfo.InvariantCulture))
                {
                    var jsonWriter = new OpenApiJsonWriter(stringWriter);
                    document.SerializeAsV3(jsonWriter);
                    return(new OkObjectResult(stringWriter.ToString()));
                }
            }
            catch (Exception ex)
            {
#if DEBUG
                return(new ObjectResult(ex.Demystify())
                {
                    StatusCode = 500
                });
#endif
                return(new ObjectResult("")
                {
                    StatusCode = 500
                });
            }
        }
        public void SerializeAdvancedRequestBodyAsV3JsonWorks()
        {
            // Arrange
            var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture);
            var writer             = new OpenApiJsonWriter(outputStringWriter);
            var expected           =
                @"{
  ""description"": ""description"",
  ""content"": {
    ""application/json"": {
      ""schema"": {
        ""type"": ""string""
      }
    }
  },
  ""required"": true
}";

            // Act
            AdvancedRequestBody.SerializeAsV3(writer);
            writer.Flush();
            var actual = outputStringWriter.GetStringBuilder().ToString();

            // Assert
            actual   = actual.MakeLineBreaksEnvironmentNeutral();
            expected = expected.MakeLineBreaksEnvironmentNeutral();
            actual.Should().Be(expected);
        }
Exemplo n.º 6
0
        public static IHost GenerateSwaggerSpecification(this IHost host)
        {
            var prov   = host.Services.GetRequiredService <ISwaggerProvider>();
            var config = host.Services.GetRequiredService <IConfiguration>();
            var patchToClientService = config["Client:PathToGenerateApi"] ??
                                       throw new ArgumentNullException("config[\"Client:PathToGenerateApi\"]",
                                                                       "Brak zdefiniowanej ścieżki do wygenerowania api");
            var swag            = prov.GetSwagger("v2");
            var swaggerFilePath = AppDomain.CurrentDomain.BaseDirectory + @"\swagger.json";

            using (var streamWriter = File.CreateText(swaggerFilePath))
            {
                IOpenApiWriter writer = new OpenApiJsonWriter(streamWriter);

                swag.SerializeAsV3(writer);
                Console.WriteLine($"Swagger JSON/YAML succesfully written to {swaggerFilePath}");
            }

            ProcessStartInfo info = new ProcessStartInfo("cmd.exe");
            var modulePrefix      = System.Reflection.Assembly.GetEntryAssembly().GetName().Name.Replace(".", "");

            info.Arguments =
                $@"/c {System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)}\SwaggerGenerator\GenerateAngularClient.cmd {patchToClientService + System.Reflection.Assembly.GetEntryAssembly().GetName().Name} {swaggerFilePath} {modulePrefix}";
            var process = Process.Start(info);

            process.WaitForExit();

            return(host);
        }
Exemplo n.º 7
0
        public void SerializeParameterWithFormStyleAndExplodeTrueWorks()
        {
            // Arrange
            var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture);
            var writer             = new OpenApiJsonWriter(outputStringWriter);
            var expected           =
                @"{
  ""name"": ""name1"",
  ""in"": ""query"",
  ""description"": ""description1"",
  ""style"": ""form"",
  ""schema"": {
    ""type"": ""array"",
    ""items"": {
      ""enum"": [
        ""value1"",
        ""value2""
      ]
    }
  }
}";

            // Act
            ParameterWithFormStyleAndExplodeTrue.SerializeAsV3WithoutReference(writer);
            writer.Flush();
            var actual = outputStringWriter.GetStringBuilder().ToString();

            // Assert
            actual   = actual.MakeLineBreaksEnvironmentNeutral();
            expected = expected.MakeLineBreaksEnvironmentNeutral();
            actual.Should().Be(expected);
        }
        public string Build(
            HttpRequest httpRequest,
            ISwaggerProvider swaggerProvider,
            string documentName)
        {
            var basePath = string.IsNullOrEmpty(httpRequest.PathBase)
                ? null
                : httpRequest.PathBase.ToString();

            var swagger =
                swaggerProvider.GetSwagger(documentName, null, basePath);

            // One last opportunity to modify the Swagger Document - this time with request context
            foreach (var filter in _options.PreSerializeFilters)
            {
                filter(swagger, httpRequest);
            }

            using (var textWriter = new StringWriter())
            {
                var jsonWriter = new OpenApiJsonWriter(textWriter);

                if (_options.SerializeAsV2)
                {
                    swagger.SerializeAsV2(jsonWriter);
                }
                else
                {
                    swagger.SerializeAsV3(jsonWriter);
                }

                return(textWriter.ToString());
            }
        }
Exemplo n.º 9
0
        public void SerializeAdvancedTagAsV2JsonWithoutReferenceWorks()
        {
            // Arrange
            var outputStringWriter = new StringWriter();
            var writer             = new OpenApiJsonWriter(outputStringWriter);
            var expected           =
                @"{
  ""name"": ""pet"",
  ""description"": ""Pets operations"",
  ""externalDocs"": {
    ""description"": ""Find more info here"",
    ""url"": ""https://example.com""
  },
  ""x-tag-extension"": null
}";

            // Act
            AdvancedTag.SerializeAsV2WithoutReference(writer);
            writer.Flush();
            var actual = outputStringWriter.GetStringBuilder().ToString();

            // Assert
            actual   = actual.MakeLineBreaksEnvironmentNeutral();
            expected = expected.MakeLineBreaksEnvironmentNeutral();
            actual.Should().Be(expected);
        }
Exemplo n.º 10
0
        public async Task <IActionResult> GetAsync()
        {
            var baseUri = "http://gateway-api/swagger/docs";
            var client  = new HttpClient();
            var doc     = new OpenApiDocument();

            doc.Paths      = new OpenApiPaths();
            doc.Components = new OpenApiComponents();
            doc.Tags       = new List <OpenApiTag>();

            foreach (var api in _ocelotSwaggerOptions.SwaggerEndpoints)
            {
                var firstConfig = api.Config[0];
                var apiUri      = $"{baseUri}/{firstConfig.Version}/{api.Key}";

                if (firstConfig.Url.StartsWith("http://orderprovider"))
                {
                    apiUri = firstConfig.Url;
                }

                var response = await client.GetAsync(apiUri);

                var responseContent = await response.Content.ReadAsStringAsync();

                var responseDoc = new OpenApiStringReader().Read(responseContent, out var diagnostic);

                foreach (var path in responseDoc.Paths)
                {
                    var pathKey = path.Key;

                    if (firstConfig.Url.StartsWith("http://orderprovider"))
                    {
                        pathKey = $"{path.Key.Replace("/api", "").ToLower()} ({firstConfig.Name})";
                    }

                    doc.Paths.Add(pathKey, path.Value);
                }

                foreach (var schema in responseDoc.Components.Schemas)
                {
                    doc.Components.Schemas.Add(schema.Key, schema.Value);
                }

                foreach (var tag in responseDoc.Tags)
                {
                    doc.Tags.Add(tag);
                }
            }

            string json;

            using (var outputString = new StringWriter())
            {
                var writer = new OpenApiJsonWriter(outputString);
                doc.SerializeAsV3(writer);
                json = outputString.ToString();
            }

            return(Ok(json));
        }
Exemplo n.º 11
0
        public void SerializeAdvancedLinkAsV3JsonWorks()
        {
            // Arrange
            var outputStringWriter = new StringWriter();
            var writer             = new OpenApiJsonWriter(outputStringWriter);
            var expected           =
                @"{
  ""operationId"": ""operationId1"",
  ""parameters"": {
    ""parameter1"": ""$request.path.id""
  },
  ""requestBody"": {
    ""property1"": true
  },
  ""description"": ""description1"",
  ""server"": {
    ""description"": ""serverDescription1""
  }
}";

            // Act
            AdvancedLink.SerializeAsV3(writer);
            writer.Flush();
            var actual = outputStringWriter.GetStringBuilder().ToString();

            // Assert
            actual   = actual.MakeLineBreaksEnvironmentNeutral();
            expected = expected.MakeLineBreaksEnvironmentNeutral();
            actual.Should().Be(expected);
        }
        public void SerializeReferencedSecuritySchemeAsV3JsonWorks()
        {
            // Arrange
            var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture);
            var writer             = new OpenApiJsonWriter(outputStringWriter);
            var expected           =
                @"{
  ""sampleSecurityScheme"": null
}";

            // Act
            // Add dummy start object, value, and end object to allow SerializeAsV3 to output security scheme
            // as property name.
            writer.WriteStartObject();
            ReferencedSecurityScheme.SerializeAsV3(writer);
            writer.WriteNull();
            writer.WriteEndObject();
            writer.Flush();
            var actual = outputStringWriter.GetStringBuilder().ToString();

            // Assert
            actual   = actual.MakeLineBreaksEnvironmentNeutral();
            expected = expected.MakeLineBreaksEnvironmentNeutral();
            actual.Should().Be(expected);
        }
Exemplo n.º 13
0
        // TODO: Handling of return type
        private async Task <bool> HandleIncomingChoice(IMessageActivity activity)
        {
            userConversation.ApiPath = await _apiParameterHandler.GetApiPath(activity.Text);

            userConversation.OperationType = await _apiParameterHandler.GetOperationType(activity.Text);

            userConversation.ParamsInfo = await _apiParameterHandler.GetParams(userConversation.ApiPath, userConversation.OperationType, userProfile.ApiObject);

            if (userConversation.OperationType == OperationType.Post)
            {
                userConversation.RequestBody = new Dictionary <string, string>();
                using (var stringWriter = new StringWriter())
                {
                    var document  = userProfile.ApiObject;
                    var writer    = new OpenApiJsonWriter(stringWriter);
                    var reference = document.Paths[userConversation.ApiPath].Operations[OperationType.Post].RequestBody.Content["application/json"].Schema.Reference;
                    var schema    = document.Components.Schemas[reference.ReferenceV3.Substring(reference.ReferenceV3.LastIndexOf('/') + 1)];
                    schema.SerializeAsV3WithoutReference(writer);
                    var requestBody = JValue.Parse(stringWriter.ToString()).ToString(Formatting.Indented);
                    userConversation.RequestBody.Add("body", requestBody);
                }
            }
            userConversation.RequestParams = userConversation.ParamsInfo.Select(param => param.Value).ToList();
            return(true);
        }
        private void WriteValueRecursive(OpenApiJsonWriter writer, object value)
        {
            if (value == null || value.GetType().IsPrimitive || value is decimal || value is string)
            {
                writer.WriteValue(value);
            }
            else if (value.GetType().IsGenericType&&
                     (typeof(IDictionary <,>).IsAssignableFrom(value.GetType().GetGenericTypeDefinition()) ||
                      typeof(Dictionary <,>).IsAssignableFrom(value.GetType().GetGenericTypeDefinition())))
            {
                writer.WriteStartObject();
                foreach (var elementValue in (dynamic)(value))
                {
                    writer.WritePropertyName(elementValue.Key);
                    WriteValueRecursive(writer, elementValue.Value);
                }

                writer.WriteEndObject();
            }
            else if (typeof(IEnumerable).IsAssignableFrom(value.GetType()))
            {
                writer.WriteStartArray();
                foreach (var elementValue in (IEnumerable)value)
                {
                    WriteValueRecursive(writer, elementValue);
                }

                writer.WriteEndArray();
            }
        }
Exemplo n.º 15
0
        public void Dispose()
        {
            if (!_options.GenerateOpenApiFiles)
            {
                return;
            }

            if (_options.FileOutputRoot == null)
            {
                throw new Exception("GenerateOpenApiFiles set but FileOutputRoot is null");
            }

            foreach (var entry in _options.OpenApiDocs)
            {
                var outputDir = Path.Combine(_options.FileOutputRoot, entry.Key);
                Directory.CreateDirectory(outputDir);

                using (var streamWriter = new StreamWriter(Path.Combine(outputDir, "openapi.json")))
                {
                    var openApiJsonWriter = new OpenApiJsonWriter(streamWriter);
                    entry.Value.SerializeAsV3(openApiJsonWriter);
                    streamWriter.Close();
                }
            }
        }
Exemplo n.º 16
0
        public void SerializeReferencedSchemaAsV3WithoutReferenceJsonWorks()
        {
            // Arrange
            var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture);
            var writer             = new OpenApiJsonWriter(outputStringWriter);

            var expected = @"{
  ""title"": ""title1"",
  ""multipleOf"": 3,
  ""maximum"": 42,
  ""minimum"": 10,
  ""exclusiveMinimum"": true,
  ""type"": ""integer"",
  ""default"": 15,
  ""nullable"": true,
  ""externalDocs"": {
    ""url"": ""http://example.com/externalDocs""
  }
}";

            // Act
            ReferencedSchema.SerializeAsV3WithoutReference(writer);
            writer.Flush();
            var actual = outputStringWriter.GetStringBuilder().ToString();

            // Assert
            actual   = actual.MakeLineBreaksEnvironmentNeutral();
            expected = expected.MakeLineBreaksEnvironmentNeutral();
            actual.Should().Be(expected);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Serializes the <see cref="IOpenApiSerializable"/> to the Open API document using
        /// the given stream, specification version and the format.
        /// </summary>
        /// <typeparam name="T">the <see cref="IOpenApiSerializable"/></typeparam>
        /// <param name="element">The Open API element.</param>
        /// <param name="stream">The given stream.</param>
        /// <param name="specVersion">The Open API specification version.</param>
        /// <param name="format">The output format (JSON or YAML).</param>
        /// <param name="settings">Provide configuration settings for controlling writing output</param>
        public static void Serialize <T>(
            this T element,
            Stream stream,
            OpenApiSpecVersion specVersion,
            OpenApiFormat format,
            OpenApiWriterSettings settings = null)
            where T : IOpenApiSerializable
        {
            if (stream == null)
            {
                throw Error.ArgumentNull(nameof(stream));
            }

            IOpenApiWriter writer;
            var            streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture);

            switch (format)
            {
            case OpenApiFormat.Json:
                writer = new OpenApiJsonWriter(streamWriter, settings);
                break;

            case OpenApiFormat.Yaml:
                writer = new OpenApiYamlWriter(streamWriter, settings);
                break;

            default:
                throw new OpenApiException(string.Format(SRResource.OpenApiFormatNotSupported, format));
            }

            element.Serialize(writer, specVersion);
        }
        /// <summary>
        /// Gets swagger json
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="documentName"></param>
        /// <param name="serializeAsV2"></param>
        /// <returns></returns>
        public static string GetSwagger(this IServiceProvider serviceProvider, string documentName, bool serializeAsV2 = false)
        {
            var requiredService = serviceProvider.GetRequiredService <ISwaggerProvider>();

            if (requiredService == null)
            {
                throw new Exception("Failed to instantiate ISwaggerProvider");
            }
            var swagger = requiredService.GetSwagger(documentName ?? "default");

            if (swagger == null)
            {
                throw new Exception("Failed to instantiate Swagger");
            }
            using (var textWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                var jsonWriter = new OpenApiJsonWriter(textWriter);
                if (serializeAsV2)
                {
                    swagger.SerializeAsV2(jsonWriter);
                }
                else
                {
                    swagger.SerializeAsV3(jsonWriter);
                }

                return(textWriter.ToString());
            }
        }
Exemplo n.º 19
0
        public static string ToJson(OpenApiDocument doc)
        {
            using var textWriter = new StringWriter();
            var jsonWriter = new OpenApiJsonWriter(textWriter);

            doc.SerializeAsV3(jsonWriter);
            return(textWriter.ToString());
        }
Exemplo n.º 20
0
        public string AsJson(OpenApiDocument document)
        {
            StringWriter      writer     = new StringWriter();
            OpenApiJsonWriter jsonWriter = new OpenApiJsonWriter(writer);

            document.SerializeAsV3(jsonWriter);
            return(writer.ToString());
        }
Exemplo n.º 21
0
        public string Index()
        {
            var            sb        = new StringBuilder();
            var            txtWriter = new StringWriter(sb);
            IOpenApiWriter writer    = new OpenApiJsonWriter(txtWriter);

            _provider.GetSwagger("v1").SerializeAsV3(writer);
            return(sb.ToString());
        }
Exemplo n.º 22
0
        public static string ConvertToJson(this OpenApiDocument document)
        {
            var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture);
            var writer             = new OpenApiJsonWriter(outputStringWriter);

            document.SerializeAsV3(writer);
            writer.Flush();
            return(outputStringWriter.GetStringBuilder().ToString());
        }
Exemplo n.º 23
0
        public void SerializeSchemaWRequiredPropertiesAsV2JsonWorks()
        {
            // Arrange
            var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture);
            var writer             = new OpenApiJsonWriter(outputStringWriter);
            var expected           = @"{
  ""title"": ""title1"",
  ""required"": [
    ""property1""
  ],
  ""properties"": {
    ""property1"": {
      ""required"": [
        ""property3""
      ],
      ""properties"": {
        ""property2"": {
          ""type"": ""integer""
        },
        ""property3"": {
          ""maxLength"": 15,
          ""type"": ""string""
        }
      }
    },
    ""property4"": {
      ""properties"": {
        ""property5"": {
          ""properties"": {
            ""property6"": {
              ""type"": ""boolean""
            }
          }
        },
        ""property7"": {
          ""minLength"": 2,
          ""type"": ""string""
        }
      },
      ""readOnly"": true
    }
  },
  ""externalDocs"": {
    ""url"": ""http://example.com/externalDocs""
  }
}";

            // Act
            AdvancedSchemaWithRequiredPropertiesObject.SerializeAsV2(writer);
            writer.Flush();
            var actual = outputStringWriter.GetStringBuilder().ToString();

            // Assert
            actual   = actual.MakeLineBreaksEnvironmentNeutral();
            expected = expected.MakeLineBreaksEnvironmentNeutral();
            actual.Should().Be(expected);
        }
Exemplo n.º 24
0
        public static string ToJson(this IOpenApiAny openApiAny)
        {
            var stringWriter = new StringWriter();
            var jsonWriter   = new OpenApiJsonWriter(stringWriter);

            openApiAny.Write(jsonWriter, OpenApiSpecVersion.OpenApi3_0);

            return(stringWriter.ToString());
        }
Exemplo n.º 25
0
        public async Task Get()
        {
            var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture);
            var writer             = new OpenApiJsonWriter(outputStringWriter);

            GetDoc().SerializeAsV3(writer);
            writer.Flush();
            await HttpContext.SendStringAsync(outputStringWriter.GetStringBuilder().ToString(), "application/json", System.Text.Encoding.UTF8);
        }
        public async Task InvokeAsHtml(HttpContext httpContext)
        {
            var response = httpContext.Response;

            response.StatusCode  = 200;
            response.ContentType = "text/html;charset=utf-8";

            if (_html == null)
            {
                var swaggerGen = httpContext.RequestServices
                                 .GetRequiredService <ISwaggerProvider>();
                _document = swaggerGen.GetSwagger(Info.Title.ToLower().Replace(' ', '_'));

                if (!_templateFile.Exists)
                {
                    throw new InvalidDataException();
                }
                using var textWriter = new StringWriter(CultureInfo.InvariantCulture);

                using (var templateReader = _templateFile.CreateReadStream())
                    using (var textReader = new StreamReader(templateReader))
                    {
                        while (true)
                        {
                            string htmlContent = await textReader.ReadLineAsync();

                            if (htmlContent == null)
                            {
                                break;
                            }
                            if (htmlContent.Contains("<%TITLE%>"))
                            {
                                htmlContent = htmlContent.Replace("<%TITLE%>", Info.Title);
                            }

                            if (!htmlContent.Contains("<%SPEC%>"))
                            {
                                textWriter.WriteLine(htmlContent);
                                continue;
                            }

                            var titleIndex = htmlContent.IndexOf("<%SPEC%>");
                            textWriter.Write(htmlContent.Substring(0, titleIndex));
                            var jsonWriter = new OpenApiJsonWriter(textWriter);
                            _document.SerializeAsV2(jsonWriter);
                            textWriter.WriteLine(htmlContent.Substring(titleIndex + 8));
                        }
                    }

                _html = textWriter.ToString();
            }

            await response.WriteAsync(_html, new UTF8Encoding(false));
        }
Exemplo n.º 27
0
        private static string Write(Action <OpenApiJsonWriter> action)
        {
            MemoryStream      stream = new MemoryStream();
            OpenApiJsonWriter writer = new OpenApiJsonWriter(new StreamWriter(stream));

            action(writer);

            writer.Flush();
            stream.Position = 0;
            return(new StreamReader(stream).ReadToEnd());
        }
        private static bool TryGetMockData(this IMockDataProvider sut, JSchema schema, out string mockData)
        {
            using (var textWriter = new StringWriter())
            {
                var writer    = new OpenApiJsonWriter(textWriter);
                var isWritten = sut.TryWriteValue(writer, schema);
                mockData = isWritten ? textWriter.ToString() : null;

                return(isWritten);
            }
        }
Exemplo n.º 29
0
        public static string GetSpecAsV2()
        {
            var outputStringWriter = new StringWriter();
            var writer             = new OpenApiJsonWriter(outputStringWriter);

            // Write V2 as JSON
            CurrentDocument.SerializeAsV2(writer);

            outputStringWriter.Flush();
            return(outputStringWriter.GetStringBuilder().ToString());
        }
Exemplo n.º 30
0
        public static string GenerateSwagger(this IWebHost webhost, string docName, string basePath)
        {
            var sw  = webhost.Services.GetRequiredService <ISwaggerProvider>();
            var doc = sw.GetSwagger(docName, null, basePath);

            using (var streamWriter = new StringWriter())
            {
                var writer = new OpenApiJsonWriter(streamWriter);
                doc.SerializeAsV3(writer);
                return(streamWriter.ToString());
            }
        }