Beispiel #1
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OpenApiTriggerFunctionProvider"/> class.
        /// </summary>
        public OpenApiHttpTriggerContext()
        {
            this.PackageAssembly = this.GetAssembly <ISwaggerUI>();

            var host = HostJsonResolver.Resolve();

            this.HttpSettings = host.GetHttpSettings();

            var filter   = new RouteConstraintFilter();
            var acceptor = new OpenApiSchemaAcceptor();
            var helper   = new DocumentHelper(filter, acceptor);

            this.Document  = new Document(helper);
            this.SwaggerUI = new SwaggerUI();
        }
        public async Task <IActionResult> RenderSwaggerDocument(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "swagger.json")] HttpRequest req)
        {
            var filter = new RouteConstraintFilter();
            var helper = new DocumentHelper(filter);

            var document = new Document(helper);
            var result   = await document.InitialiseDocument()
                           .AddMetadata(_settings.OpenApiInfo)
                           .AddServer(req, "api")
                           .Build(Assembly.GetExecutingAssembly(), new DefaultNamingStrategy())
                           .RenderAsync(OpenApiSpecVersion.OpenApi2_0, OpenApiFormat.Json)
                           .ConfigureAwait(false);

            var response = new ContentResult()
            {
                Content     = result,
                ContentType = "application/json",
                StatusCode  = (int)HttpStatusCode.OK
            };

            return(response);
        }
        public async Task <IActionResult> RenderSwaggerDocument(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "swagger/{version}.{format}")] HttpRequest request, string version, string format, ILogger logger)
        {
            logger.LogInformation("Configuring swagger document...");

            var openApiSettings = _serviceProvider.GetService <OpenApiAppSettings>();

            var filter   = new RouteConstraintFilter();
            var helper   = new DocumentHelper(filter);
            var document = new Document(helper);

            var result = await document.InitialiseDocument()
                         .AddMetadata(openApiSettings.OpenApiInfo)
                         .AddServer(request, routePrefix: "api")
                         .Build(Assembly.GetExecutingAssembly(), new CamelCaseNamingStrategy())
                         .RenderAsync(GetVersion(version), GetFormat(format));

            return(new ContentResult()
            {
                Content = result,
                ContentType = "application/json",
                StatusCode = (int)HttpStatusCode.OK
            });
        }
Beispiel #4
0
        /// <summary>
        /// Generates the OpenAPI document.
        /// </summary>
        /// <param name="project">Project path.</param>
        /// <param name="configuration">Copile configuration.</param>
        /// <param name="version">OpenAPI version.</param>
        /// <param name="format">OpenAPI output format.</param>
        /// <param name="output">Output path.</param>
        /// <param name="console">Value indicating whether to render the document on console or not.</param>
        public void Generate(
            [Option('p', Description = "Project path. Default is current directory")] string project  = ".",
            [Option('c', Description = "Configuration. Default is 'Debug'")] string configuration     = "Debug",
            [Option('t', Description = "Target framework. Default is 'netcoreapp2.1'")] string target = "netcoreapp2.1",
            [Option('v', Description = "OpenAPI spec version. Value can be either 'v2' or 'v3'. Default is 'v2'")] OpenApiVersionType version      = OpenApiVersionType.V2,
            [Option('f', Description = "OpenAPI output format. Value can be either 'json' or 'yaml'. Default is 'yaml'")] OpenApiFormatType format = OpenApiFormatType.Json,
            [Option('o', Description = "Generated OpenAPI output location. Default is 'output'")] string output = "output",
            bool console = false)
        {
            var pi = default(ProjectInfo);

            try
            {
                pi = new ProjectInfo(project, configuration, target);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);

                return;
            }

            var req = new Mock <HttpRequest>();

            req.SetupGet(p => p.Scheme).Returns("http");
            req.SetupGet(p => p.Host).Returns(new HostString("localhost", 7071));

            var filter         = new RouteConstraintFilter();
            var acceptor       = new OpenApiSchemaAcceptor();
            var namingStrategy = new CamelCaseNamingStrategy();
            var collection     = VisitorCollection.CreateInstance();
            var helper         = new DocumentHelper(filter, acceptor);
            var document       = new Document(helper);

            var swagger = default(string);

            try
            {
                swagger = document.InitialiseDocument()
                          .AddMetadata(pi.OpenApiInfo)
                          .AddServer(req.Object, pi.HostJsonHttpSettings.RoutePrefix)
                          .AddNamingStrategy(namingStrategy)
                          .AddVisitors(collection)
                          .Build(pi.CompiledDllPath)
                          .RenderAsync(version.ToOpenApiSpecVersion(), format.ToOpenApiFormat())
                          .Result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }

            if (console)
            {
                Console.WriteLine(swagger);
            }

            var outputpath = Path.IsPathFullyQualified(output)
                                 ? output
                                 : $"{pi.CompiledPath}{directorySeparator}{output}";

            if (!Directory.Exists(outputpath))
            {
                Directory.CreateDirectory(outputpath);
            }

            File.WriteAllText($"{outputpath}{directorySeparator}swagger.{format.ToDisplayName()}", swagger, Encoding.UTF8);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="DocumentHelper"/> class.
 /// </summary>
 /// <param name="filter"><see cref="RouteConstraintFilter"/> instance.</param>
 /// <param name="acceptor"><see cref="IAcceptor"/> instance.</param>
 public DocumentHelper(RouteConstraintFilter filter, IOpenApiSchemaAcceptor acceptor)
 {
     this._filter   = filter.ThrowIfNullOrDefault();
     this._acceptor = acceptor.ThrowIfNullOrDefault();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DocumentHelper"/> class.
 /// </summary>
 /// <param name="filter"><see cref="RouteConstraintFilter"/> instance.</param>
 public DocumentHelper(RouteConstraintFilter filter)
 {
     this._filter = filter.ThrowIfNullOrDefault();
 }