示例#1
0
        public static async Task <IActionResult> RenderSwaggerUI(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "swagger/ui")] HttpRequest req,
            ILogger log)
        {
            var ui       = new SwaggerUI();
            var metaData = new OpenApiInfo {
                Version = "1.0.0",
                Title   = "Azure Functions Hello World",
                License = new OpenApiLicense {
                    Name = "None"
                },
                Contact = new OpenApiContact {
                    Email = "*****@*****.**",
                    Url   = new Uri("https://github.com/NtFreX/HelloAzureFunctions")
                }
            };

            var result = await ui
                         .AddServer(req, ApiPrefix)
                         .AddMetadata(metaData)
                         .BuildAsync()
                         .RenderAsync("swagger.json")
                         .ConfigureAwait(false);

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

            return(response);
        }
        public async Task <IActionResult> GenerateDocumentationInterface([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "docs")] HttpRequest req)
        {
            _ = req ?? throw new ArgumentNullException(nameof(req));

            var assembly = Assembly.GetExecutingAssembly();
            var authCode = req.Query[AuthenticationParameter];
            var fileVersionInformation = FileVersionInfo.GetVersionInfo(assembly.Location);
            var swaggerUi = new SwaggerUI();
            var result    = await swaggerUi
                            .AddMetadata(new OpenApiInfo()
            {
                Title       = fileVersionInformation.ProductName,
                Description = fileVersionInformation.Comments,
                Contact     = new OpenApiContact()
                {
                    Name = fileVersionInformation.CompanyName
                },
                Version = fileVersionInformation.FileVersion,
            })
                            .AddServer(req, "api")
                            .BuildAsync()
                            .RenderAsync("openapi.json", authCode);

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

            return(response);
        }
        public async Task Given_AuthKey_Options_When_RenderAsync_Invoked_Then_It_Should_Be_Used_As_Request_Key(
            string queryKey, OpenApiAuthLevelType configuredAuthLevel, string configKey, string expectedRequestKey,
            bool throwsException = false)
        {
            var endpoint = "swagger/ui";
            var baseUrl  = "https://localhost:7071";
            var ui       = new SwaggerUI();

            ui.AddMetadata(new OpenApiInfo());
            var uiType = ui.GetType();

            //Generate Request Object with query key
            var queryDict = new Dictionary <string, StringValues>();

            if (queryKey != null)
            {
                queryDict["code"] = queryKey;
            }
            var req = new Mock <IHttpRequestDataObject>();

            req.SetupGet(p => p.Query).Returns(new QueryCollection(queryDict));
            uiType.GetField("_req", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(ui, req.Object);

            //Set BaseUrl
            uiType.GetField("_baseUrl", BindingFlags.Instance | BindingFlags.NonPublic).SetValue(ui, baseUrl);

            //Set html string just to contain url placeholder
            var swaggerUrlPlaceholder =
                uiType.GetField("SwaggerUrlPlaceholder", BindingFlags.Static | BindingFlags.NonPublic)
                .GetRawConstantValue() as string;

            uiType.GetField("_indexHtml", BindingFlags.Instance | BindingFlags.NonPublic)
            .SetValue(ui, swaggerUrlPlaceholder);


            Func <Task <string> > action = async() => await ui.RenderAsync(endpoint, configuredAuthLevel, configKey);

            if (throwsException)
            {
                await action.Should().ThrowAsync <InvalidOperationException>();
            }
            else
            {
                var result = await action();

                if (expectedRequestKey != null)
                {
                    result.Should().Contain($"code={expectedRequestKey}");
                }
                else
                {
                    result.Should().NotContain($"code=");
                }
            }
        }
示例#4
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app">The application.</param>
        /// <param name="env">The env.</param>
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            string url = string.Empty;

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors("AllowOrigin");

            app.UseAuthorization();

            app.UseSwagger();
            app.UseSwaggerUI(SwaggerUI => {
                if (_env.IsDevelopment())
                {
                    url = "/swagger/v1/swagger.json";
                }
                else
                {
                    url = "../swagger/v1/swagger.json";
                }

                SwaggerUI.SwaggerEndpoint(url, "Zoo Management Service v1.0.0");
            });

            var option = new RewriteOptions();

            option.AddRedirect("^$", "swagger");
            app.UseRewriter(option);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.EnableDependencyInjection();
                endpoints.Expand().Select().Filter().Count().MaxTop(1000);
            });

            #region Migartion Auto
            // Create database on startup
            //using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
            //{
            //    serviceScope.ServiceProvider.GetService<ZooContext>().Database.Migrate();
            //}
            #endregion
        }
示例#5
0
        public async Task <IActionResult> RenderOpenApiUI(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "swagger/ui")] HttpRequest req)
        {
            var ui     = new SwaggerUI();
            var result = await(await ui.AddMetadata(_swaggerMetadata)
                               .AddServer(req, "api")
                               .BuildAsync())
                         .RenderAsync("swagger.json")
                         .ConfigureAwait(false);

            return(new ContentResult
            {
                Content = result,
                ContentType = "text/html",
                StatusCode = StatusCodes.Status200OK
            });
        }
示例#6
0
        public void Given_NullOptions_When_AddServer_Invoked_Then_It_Should_Return_BaseUrl(string scheme, string host, string routePrefix, string expected)
        {
            var req = new Mock <IHttpRequestDataObject>();

            req.SetupGet(p => p.Scheme).Returns(scheme);

            var hostString = new HostString(host);

            req.SetupGet(p => p.Host).Returns(hostString);

            var ui = new SwaggerUI();

            ui.AddServer(req.Object, routePrefix, null);

            var fi = ui.GetType().GetField("_baseUrl", BindingFlags.Instance | BindingFlags.NonPublic);

            (fi.GetValue(ui) as string).Should().Be(expected);
        }
        public void Given_Options_When_IsAuthKeyRequired_Invoked_Then_It_Should_Return_Result(
            OpenApiAuthLevelType configuredAuthLevel, string configKey, bool throwsException, bool expected)
        {
            var ui     = new SwaggerUI();
            var method = ui.GetType()
                         .GetMethod("IsAuthKeyRequired", BindingFlags.Instance | BindingFlags.NonPublic);

            Func <bool> action = () => (bool)method.Invoke(ui, new object[] { configuredAuthLevel, configKey });

            if (throwsException)
            {
                action.Should().Throw <TargetInvocationException>().And.InnerException.Should()
                .BeOfType <InvalidOperationException>();
            }
            else
            {
                action.Invoke().Should().Be(expected);
            }
        }
        public async Task <IActionResult> RenderSwaggerUI(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "swagger/ui")] HttpRequest req)
        {
            var ui     = new SwaggerUI();
            var result = await ui.AddMetadata(_settings.OpenApiInfo)
                         .AddServer(req, "")
                         .BuildAsync()
                         .RenderAsync("api/swagger.json", _settings.SwaggerAuthKey)
                         .ConfigureAwait(false);

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

            return(response);
        }
示例#9
0
        public static async Task <IActionResult> RenderSwaggerUI(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "openapi/ui")] HttpRequest req,
            ILogger log)
        {
            var settings = new AppSettings();
            var ui       = new SwaggerUI();
            var result   = await(await ui.AddMetadata(settings.OpenApiInfo)
                                 .AddServer(req, settings.HttpSettings.RoutePrefix)
                                 .BuildAsync())
                           .RenderAsync("swagger", settings.SwaggerAuthKey)
                           .ConfigureAwait(false);
            var response = new ContentResult()
            {
                Content     = result,
                ContentType = "text/html",
                StatusCode  = (int)HttpStatusCode.OK
            };

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

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

            var ui     = new SwaggerUI();
            var result = await ui.AddMetadata(openApiSettings.OpenApiInfo)
                         .AddServer(request, routePrefix: "api")
                         .BuildAsync()
                         .RenderAsync($"swagger/{version}.{format}", openApiSettings.SwaggerAuthKey);

            return(new ContentResult()
            {
                Content = result,
                ContentType = "text/html",
                StatusCode = (int)HttpStatusCode.OK
            });
        }
        public void Given_NullOptions_When_AddServer_Invoked_Then_It_Should_Return_SwaggerUIApiPrefix(string scheme, string host, string routePrefix, bool optionsSet, string expected)
        {
            var req = new Mock <IHttpRequestDataObject>();

            req.SetupGet(p => p.Scheme).Returns(scheme);

            var hostString = new HostString(host);

            req.SetupGet(p => p.Host).Returns(hostString);

            var ui      = new SwaggerUI();
            var options = new Mock <IOpenApiConfigurationOptions>();

            options.SetupGet(p => p.Servers).Returns(new List <OpenApiServer>());
            ui.AddServer(req.Object, routePrefix, optionsSet ? options.Object: null);

            var fi = ui.GetType().GetField("_swaggerUiApiPrefix", BindingFlags.Instance | BindingFlags.NonPublic);

            (fi.GetValue(ui) as string).Should().Be(expected);
        }
示例#12
0
        public static async Task <IActionResult> RenderSwaggerUI(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = "swagger")] HttpRequest request,
            ILogger log)
        {
            var ui     = new SwaggerUI();
            var result = await ui.AddMetadata(GetOpenApiInfo())
                         .AddServer(request, "api")
                         .BuildAsync()
                         .RenderAsync("openapi/json", null)
                         .ConfigureAwait(false);

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

            return(response);
        }
示例#13
0
        public async Task <string> GetSwaggerUIContentAsync(HttpRequest httpRequest, string documentName, string authCode, Assembly assembly)
        {
            _ = assembly ?? throw new ArgumentNullException(nameof(assembly));

            var fileVersionInformation = FileVersionInfo.GetVersionInfo(assembly.Location);
            var swaggerUi = new SwaggerUI();
            var result    = await swaggerUi
                            .AddMetadata(new OpenApiInfo()
            {
                Title       = fileVersionInformation.ProductName,
                Description = fileVersionInformation.Comments,
                Contact     = new OpenApiContact()
                {
                    Name = fileVersionInformation.CompanyName
                },
                Version = fileVersionInformation.FileVersion,
            })
                            .AddServer(httpRequest, RoutePrefix)
                            .BuildAsync()
                            .RenderAsync(documentName, authCode);

            return(result);
        }