public void UsesTheDesiredRoute()
        {
            // Arrange
            var options = new HealthCheckOptions
            {
                Route = "/my/custom/healthcheck"
            };
            var module = new HealthCheckModule(Enumerable.Empty<IChecker>(), options);
            var bootstrapper = new ConfigurableBootstrapper(with =>
            {
                with.Module(module);
            });
            var browser = new Browser(bootstrapper);

            // Act
            var response = browser.Get(options.Route, with =>
            {
                with.HttpsRequest();
            });

            // Assert
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
        }
        /// <summary>
        /// Use health check middleware with pre-defined options:
        /// * ResponseWriter: Include each dependency's status and elapsed time in response
        /// * Endpoint: /HealthCheck
        /// </summary>
        /// <param name="app">Application builder</param>
        /// <param name="setupAction">change pre-defined options</param>
        /// <param name="path">change pre-defined healthcheck endpoint path</param>
        /// <returns></returns>
        public static IApplicationBuilder UseCustomHealthChecks(this IApplicationBuilder app, Action <HealthCheckOptions> setupAction = null, string path = null)
        {
            var options = new HealthCheckOptions
            {
                ResponseWriter = async(c, r) =>
                {
                    c.Response.ContentType = MediaTypeNames.Application.Json;
                    var result = JsonConvert.SerializeObject(
                        new
                    {
                        status = r.Status.ToString(),
                        checks = r.Entries.Select(e =>
                                                  new
                        {
                            description  = e.Key,
                            status       = e.Value.Status.ToString(),
                            responseTime = e.Value.Duration.TotalMilliseconds
                        }),
                        totalResponseTime = r.TotalDuration.TotalMilliseconds
                    });
                    await c.Response.WriteAsync(result);
                }
            };

            setupAction?.Invoke(options);

            return(app.UseHealthChecks(path ?? "/healthcheck", options));
        }
Ejemplo n.º 3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            var options = new HealthCheckOptions
            {
                AllowCachingResponses = true,
                ResponseWriter        = WriteResponse
            };

            app.UseHealthChecks("/v1/healthcheck", options);

            app.UseSwagger(c =>
            {
                c.RouteTemplate = "api-docs/v1/swagger.json";
            });
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/api-docs/v1/swagger.json", "My API V1");
            });

            app.UseRouting();

            app.UseAuthorization();

            app.UseMvc();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
Ejemplo n.º 4
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMapper mapper)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            mapper.ConfigurationProvider.AssertConfigurationIsValid();

            HealthCheckOptions options = new HealthCheckOptions
            {
                ResponseWriter = async(c, r) =>
                {
                    string result = JsonConvert.SerializeObject(new
                    {
                        status = r.Status.ToString(),
                        checks = r.Entries.Select(e => new
                        {
                            key   = e.Key,
                            value = e.Value.Status.ToString(),
                        }),
                    });

                    c.Response.ContentType = "application/json";
                    await c.Response.WriteAsync(result);
                },
            };

            app.UseHealthChecks("/health", options);

            app.UseMvc();
        }
Ejemplo n.º 5
0
        public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder application)
        {
            var healthCheckOptions = new HealthCheckOptions
            {
                ResponseWriter = async(a, b) =>
                {
                    a.Response.ContentType = MediaTypeNames.Application.Json;
                    var result = JsonConvert.SerializeObject(
                        new
                    {
                        checks = b.Entries.Select(e =>
                                                  new
                        {
                            description  = e.Key,
                            status       = e.Value.Status.ToString(),
                            responseTime = e.Value.Duration.TotalMilliseconds
                        }),
                        totalResponseTime = b.TotalDuration.TotalMilliseconds,
                        status            = b.Entries.Any(a => a.Value.Status != HealthStatus.Healthy) ?
                                            b.Entries.Any(a => a.Value.Status == HealthStatus.Unhealthy) ? HealthStatus.Unhealthy.ToString() : HealthStatus.Degraded.ToString()
                            : HealthStatus.Healthy.ToString()
                    });
                    await a.Response.WriteAsync(result);
                }
            };

            return(application.UseHealthChecks("/health", healthCheckOptions));
        }
        public async Task ShouldRespondWith503StatusCodeWithFailureJsonString()
        {
            //Arrange
            var next = GetRequestDelegate();

            var httpContext = new DefaultHttpContext();

            httpContext.Response.Body = new MemoryStream();

            var options = new HealthCheckOptions()
            {
                Path = "/healthcheck"
            };

            httpContext.Request.Path = "/healthcheck";

            var healthCheckMiddleware = new HealthCheckMiddleware(next, _failingHealthChecker, options);

            //Act
            await healthCheckMiddleware.Invoke(httpContext);

            //Assert
            httpContext.Response.StatusCode.ShouldBe(503);
            Assert.IsTrue(ReadBodyAsString(httpContext).Contains("FailingHealthCheck"));
        }
        public async Task ShouldRespondWith200StatusCodeWithSuccessJsonString()
        {
            //Arrange
            var next = GetRequestDelegate();

            var httpContext = new DefaultHttpContext();

            httpContext.Response.Body = new MemoryStream();

            var options = new HealthCheckOptions()
            {
                Path = "/healthcheck"
            };

            httpContext.Request.Path = "/healthcheck";

            var healthCheckMiddleware = new HealthCheckMiddleware(next, _healthChecker, options);

            //Act
            await healthCheckMiddleware.Invoke(httpContext);

            //Assert
            httpContext.Response.StatusCode.ShouldBe(200);
            httpContext.Response.ContentType.ShouldBe("text/plain");
            httpContext.Response.Headers["Content-Disposition"].ToString().ShouldBe("inline");
            httpContext.Response.Headers["Cache-Control"].ToString().ShouldBe("no-cache");

            Assert.IsTrue(ReadBodyAsString(httpContext).Contains("Checks whether the application is running. If this check can run then it should pass."));
        }
Ejemplo n.º 8
0
        private static HealthCheckOptions CreateHealthCheckOptions()
        {
            var options = new HealthCheckOptions
            {
                ResponseWriter = async(ctx, rpt) =>
                {
                    var result = JsonConvert.SerializeObject(new
                    {
                        status = rpt.Status.ToString(),
                        checks = rpt.Entries.Select(e => new
                        {
                            service = e.Key,
                            status  = Enum.GetName(typeof(HealthStatus),
                                                   e.Value.Status),
                            error     = e.Value.Exception?.Message,
                            incidents = e.Value.Data
                        }),
                    },
                                                             Formatting.None, new JsonSerializerSettings()
                    {
                        NullValueHandling = NullValueHandling.Ignore
                    });

                    ctx.Response.ContentType = MediaTypeNames.Application.Json;
                    await ctx.Response.WriteAsync(result);
                }
            };

            return(options);
        }
Ejemplo n.º 9
0
        public static void Main()
        {
            var random  = new Random();
            var options = new HealthCheckOptions
            {
                ResultStatusCodes = new Dictionary <HealthStatus, int>
                {
                    [HealthStatus.Healthy]   = 299,
                    [HealthStatus.Degraded]  = 298,
                    [HealthStatus.Unhealthy] = 503
                }
            };

            Host.CreateDefaultBuilder()
            .ConfigureWebHostDefaults(builder => builder
                                      .ConfigureServices(svcs => svcs.AddHealthChecks().AddCheck("default", Check))
                                      .Configure(app => app.UseHealthChecks("/healthcheck", options)))
            .Build()
            .Run();

            HealthCheckResult Check()
            {
                return((random.Next(1, 4)) switch
                {
                    1 => HealthCheckResult.Unhealthy(),
                    2 => HealthCheckResult.Degraded(),
                    _ => HealthCheckResult.Healthy(),
                });
            }
Ejemplo n.º 10
0
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseCors("CorsPolicy");

            app.UseAuthentication();

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

            app.UseHttpStatusCodeExceptionMiddleware();

            app.UseSwagger();

            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "Kids Toy Hive Api");
                options.RoutePrefix = string.Empty;
            });
            var options = new HealthCheckOptions();

            app.UseHealthChecks("/hc");

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseEndpoints(endpoints => {
                endpoints.MapControllers();
            });
        }
        /// <summary>
        /// 应用AspNetCore的服务业务
        /// </summary>
        /// <param name="app">Asp应用程序构建器</param>
        public override void UsePack(IApplicationBuilder app)
        {
            IServiceProvider provider      = app.ApplicationServices;
            IConfiguration   configuration = provider.GetService <IConfiguration>();
            bool             enabled       = configuration["OSharp:HealthChecks:Enabled"].CastTo(false);

            if (!enabled)
            {
                return;
            }

            string             url     = configuration["OSharp:HealthChecks:Url"] ?? "/health";
            HealthCheckOptions options = GetHealthCheckOptions(provider);

            if (options != null)
            {
                app.UseHealthChecks(url, options);
            }
            else
            {
                app.UseHealthChecks(url);
            }

            IsEnabled = true;
        }
Ejemplo n.º 12
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            var options = new HealthCheckOptions();

            options.ResponseWriter = async(c, r) => {
                c.Response.ContentType = "application/json";

                var result = JsonConvert.SerializeObject(new
                {
                    status = r.Status.ToString(),
                    errors = r.Entries.Select(e => new { key = e.Key, value = e.Value.Status.ToString() })
                });

                await c.Response.WriteAsync(result);
            };

            app.UseHealthChecks("/hc");

            app.UseHttpsRedirection();
            app.UseMvc();
        }
Ejemplo n.º 13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                var options = new HealthCheckOptions
                {
                    ResponseWriter = async(c, r) =>
                    {
                        c.Response.ContentType = "application/json";

                        var result = JsonSerializer.Serialize(new
                        {
                            status        = r.Status.ToString(),
                            statusDetails = r.Entries.Select(e => new { key = e.Key, value = e.Value.Status.ToString() })
                        });
                        await c.Response.WriteAsync(result);
                    }
                };
                endpoints.MapHealthChecks("/health", options);
                endpoints.MapControllers();
            });
        }
        public IServiceBusNamespace CreateClient(HealthCheckOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var azureClient = AzureClient.Configure()
                              .WithLogLevel(options)
                              .WithUserAgent(options)
                              .Authenticate(options.ServiceCredentials)
                              .WithSubscription(options);

            // TODO :: Use Async Overloads
            IServiceBusNamespace sbNamespace;

            if (Guid.TryParse(options.Namespace, out var _))
            {
                sbNamespace = azureClient.ServiceBusNamespaces.GetById(options.Namespace);
            }
            else
            {
                sbNamespace = azureClient.ServiceBusNamespaces.List().FirstOrDefault(x => x.Name.Equals(options.Namespace, StringComparison.OrdinalIgnoreCase));
            };

            if (sbNamespace == null)
            {
                throw new Exception($"Unable to locate service by namespace: '{options.Namespace}'");
            }

            return(sbNamespace);
        }
        public static void UseHmcrHealthCheck(this IApplicationBuilder app)
        {
            var healthCheckOptions = new HealthCheckOptions
            {
                ResponseWriter = async(c, r) =>
                {
                    c.Response.ContentType = MediaTypeNames.Application.Json;
                    var result = JsonSerializer.Serialize(
                        new
                    {
                        checks = r.Entries.Select(e =>
                                                  new {
                            description  = e.Key,
                            status       = e.Value.Status.ToString(),
                            tags         = e.Value.Tags,
                            responseTime = e.Value.Duration.TotalMilliseconds
                        }),
                        totalResponseTime = r.TotalDuration.TotalMilliseconds
                    });
                    await c.Response.WriteAsync(result);
                }
            };

            app.UseHealthChecks("/healthz", healthCheckOptions);
        }
Ejemplo n.º 16
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHealthChecks("/ping", new HealthCheckOptions()
            {
                Predicate = _ => false
            });

            HealthCheckOptions options = new HealthCheckOptions();

            options.ResultStatusCodes[HealthStatus.Degraded] = 418; // I'm a tea pot (or other HttpStatusCode enum)
            options.AllowCachingResponses = true;
            options.Predicate             = _ => true;
            options.ResponseWriter        = UIResponseWriter.WriteHealthCheckUIResponse;
            app.UseHealthChecks("/health", options);

            app.UseHealthChecksUI();
            //app.UseHealthChecksUI(setup =>
            //{
            //    setup.UIPath = "/show-health-ui"; // this is ui path in your browser
            //    setup.ApiPath = "/health-ui-api"; // the UI ( spa app )  use this path to get information from the store ( this is NOT the healthz path, is internal ui api )
            //});
            app.UseHttpsRedirection();
            app.UseMvc();
        }
Ejemplo n.º 17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            var queues = new[] { "default", "apis", "localjobs" };

            app.UseHangfireServer(new BackgroundJobServerOptions()
            {
                ShutdownTimeout = TimeSpan.FromMinutes(30),                //等待所有任务执行的时间当服务被关闭时
                Queues          = queues,                                  //队列
                WorkerCount     = Math.Max(Environment.ProcessorCount, 20) //工作线程数,当前允许的最大线程,默认20
            });
            app.UseHangfireDashboard("/job", new DashboardOptions
            {
                AppPath       = HangfireSettings.Instance.AppWebSite,//返回时跳转的地址
                Authorization = new[] { new BasicAuthAuthorizationFilter(new BasicAuthAuthorizationFilterOptions
                    {
                        RequireSsl         = false,//是否启用ssl验证,即https
                        SslRedirect        = false,
                        LoginCaseSensitive = true,
                        Users = new []
                        {
                            new BasicAuthAuthorizationUser
                            {
                                Login         = HangfireSettings.Instance.LoginUser, //登录账号
                                PasswordClear = HangfireSettings.Instance.LoginPwd   //登录密码
                            }
                        }
                    }) }
            });
            //重写json报告数据,可用于远程调用获取健康检查结果
            var options = new HealthCheckOptions();

            options.ResponseWriter = async(c, r) =>
            {
                c.Response.ContentType = "application/json";

                var result = JsonConvert.SerializeObject(new
                {
                    status = r.Status.ToString(),
                    errors = r.Entries.Select(e => new { key = e.Key, value = e.Value.Status.ToString() })
                });
                await c.Response.WriteAsync(result);
            };

            app.UseHealthChecks("/healthz", new HealthCheckOptions()
            {
                Predicate      = _ => true,
                ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
            });
            app.UseHealthChecks("/health", options);//获取自定义格式的json数据
            app.UseHealthChecksUI(setup =>
            {
                setup.UIPath  = "/hc";     // 健康检查的UI面板地址
                setup.ApiPath = "/hc-api"; // 用于api获取json的检查数据
            });
            app.UseMvc();
        }
        public void Equals_Different_Value_Returns_False()
        {
            // Arrange
            var options1 = new HealthCheckOptions
            {
                Enabled  = true,
                Interval = TimeSpan.FromSeconds(2),
                Timeout  = TimeSpan.FromSeconds(1),
                Port     = 123,
                Path     = "/a",
            };

            var options2 = new HealthCheckOptions
            {
                Enabled  = false,
                Interval = TimeSpan.FromSeconds(4),
                Timeout  = TimeSpan.FromSeconds(2),
                Port     = 246,
                Path     = "/b",
            };

            // Act
            var equals = HealthCheckOptions.Equals(options1, options2);

            // Assert
            Assert.False(equals);
        }
Ejemplo n.º 19
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            var options = new HealthCheckOptions();

            options.ResultStatusCodes[HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable;

            options.ResponseWriter = async(context, report) =>
            {
                var result = JsonConvert.SerializeObject(new
                {
                    status = report.Status.ToString(),
                    errors = report.Entries.Select(e => new { key = e.Key, value = Enum.GetName(typeof(HealthStatus), e.Value.Status) })
                }, Formatting.None, new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore
                });
                context.Response.ContentType = MediaTypeNames.Application.Json;
                await context.Response.WriteAsync(result);
            };

            app.UseAuthentication();
            app.UseHealthChecks("/hc", options);
            app.UseOcelot();
            app.UseMvc();
        }
        public DiagnosticsController(HealthCheckService healthCheckService, IMapper mapper, HealthCheckOptions healthCheckOptions = null)
        {
            _healthCheckService = healthCheckService ?? throw new ArgumentNullException(nameof(healthCheckService));

            _healthCheckOptions = healthCheckOptions ?? new HealthCheckOptions();
            _mapper             = mapper ?? throw new ArgumentNullException(nameof(mapper));
        }
Ejemplo n.º 21
0
        public static void MapHealthChecksWithJsonResponse(this IEndpointRouteBuilder endpoints, PathString path)
        {
            var options = new HealthCheckOptions
            {
                ResponseWriter = async(httpContext, healthReport) =>
                {
                    httpContext.Response.ContentType = "application/json";

                    var result = JsonConvert.SerializeObject(new
                    {
                        status = healthReport.Status.ToString(),
                        totalDurationInSeconds = healthReport.TotalDuration.TotalSeconds,
                        entries = healthReport.Entries.Select(e => new
                        {
                            key         = e.Key,
                            status      = e.Value.Status.ToString(),
                            description = e.Value.Description,
                            data        = e.Value.Data,
                            exception   = e.Value.Exception
                        })
                    });
                    await httpContext.Response.WriteAsync(result);
                }
            };

            endpoints.MapHealthChecks(path, options);
        }
        public static IApplicationBuilder UseHealthChecks(this IApplicationBuilder app)
        {
            var options = new HealthCheckOptions
            {
                AllowCachingResponses = false,
                ResponseWriter        = async(context, report) =>
                {
                    var result = JsonConvert.SerializeObject(
                        new
                    {
                        status = report.Status.ToString(),
                        errors = report.Entries.Select(e =>
                                                       new
                        {
                            key   = e.Key,
                            value = Enum.GetName(typeof(HealthStatus),
                                                 e.Value.Status)
                        })
                    });
                    context.Response.ContentType = MediaTypeNames.Application.Json;
                    await context.Response.WriteAsync(result);
                }
            };

            options.ResultStatusCodes[HealthStatus.Unhealthy] = 500;
            options.ResultStatusCodes[HealthStatus.Degraded]  = 500;

            //Adicionando endpoint para Middleware checar a saúde do serviço
            app.UseHealthChecks("/health", options);

            return(app);
        }
        public static IApplicationBuilder UseCustomHealthCheck(this IApplicationBuilder builder, string apiName, string path)
        {
            var healthCheckOptions = new HealthCheckOptions
            {
                ResponseWriter = async(context, report) =>
                {
                    context.Response.ContentType = MediaTypeNames.Application.Json;

                    var result = JsonConvert.SerializeObject(new
                    {
                        api           = apiName,
                        version       = Assembly.GetExecutingAssembly().GetName().Version.ToString(),
                        health_checks = report.Entries.Select(e => new
                        {
                            description = e.Key,
                            state       = (e.Value.Status == HealthStatus.Healthy).ToString(),
                        }),
                    });

                    await context.Response.WriteAsync(result);
                }
            };

            return(builder.UseHealthChecks(new PathString(path), healthCheckOptions));
        }
        public static IApplicationBuilder UseJsonHealthChecks(this IApplicationBuilder app)
        {
            var options = new HealthCheckOptions
            {
                ResponseWriter = async(context, report) =>
                {
                    var statusObject = new
                    {
                        Status = report.Status.ToString(),
                        Errors = report.Entries.Select(error => new
                        {
                            HealthCheckName = error.Key,
                            Description     = error.Value.Description
                        })
                    };

                    var json = JsonConvert.SerializeObject(statusObject);
                    context.Response.ContentType = MediaTypeNames.Application.Json;
                    await context.Response.WriteAsync(json);
                }
            };

            app.UseHealthChecks("/healthcheck", options);

            return(app);
        }
        public async Task be_unhealthy_when_using_configuration_auto_with_an_invalid_imap_port()
        {
            var webHostBuilder = new WebHostBuilder()
                                 .UseStartup <DefaultStartup>()
                                 .ConfigureServices(services =>
            {
                services.AddHealthChecks()
                .AddImapHealthCheck(setup =>
                {
                    setup.Host = _host;
                    setup.Port = 135;
                }, tags: new string[] { "imap" });
            })
                                 .Configure(app =>
            {
                var options = new HealthCheckOptions()
                {
                    Predicate = r => r.Tags.Contains("imap")
                };
                options.ResultStatusCodes[HealthStatus.Unhealthy] = (int)HttpStatusCode.ServiceUnavailable;

                app.UseHealthChecks("/health", options);
            });

            var server   = new TestServer(webHostBuilder);
            var response = await server.CreateRequest("/health")
                           .GetAsync();

            response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable);
        }
Ejemplo n.º 26
0
        public static HealthCheckOptions HealthCheckOpts()
        {
            HealthCheckOptions options = new HealthCheckOptions();
            var json = "";

            options.AllowCachingResponses = false;
            options.ResponseWriter        = async(context, report) =>
            {
                context.Response.ContentType = "application/json";
                List <HealthCheckServiceStatus> result = new List <HealthCheckServiceStatus>();
                result.Add(new HealthCheckServiceStatus {
                    Service = "OverAll", StatusNumber = (int)report.Status, Status = report.Status.ToString()
                });
                result.AddRange(
                    report.Entries.Select(
                        e => new HealthCheckServiceStatus
                {
                    Service      = e.Key,
                    StatusNumber = (int)e.Value.Status,
                    Status       = report.Status.ToString(),
                    Data         = e.Value.Data.Select(k => k).ToList(),
                }
                        ));

                json = JsonConvert.SerializeObject(result);

                await context.Response.WriteAsync(json);
            };

            return(options);
        }
Ejemplo n.º 27
0
        protected virtual void ConfigureHealthCheck(IApplicationBuilder app)
        {
            // Health check output
            var healthCheckOptions = new HealthCheckOptions
            {
                ResponseWriter = async(c, r) =>
                {
                    c.Response.ContentType = MediaTypeNames.Application.Json;

                    var result = JsonConvert.SerializeObject(
                        new
                    {
                        checks = r.Entries.Select(e =>
                                                  new
                        {
                            description  = e.Key,
                            status       = e.Value.Status.ToString(),
                            responseTime = e.Value.Duration.TotalMilliseconds
                        }),
                        totalResponseTime = r.TotalDuration.TotalMilliseconds
                    });

                    await c.Response.WriteAsync(result);
                }
            };

            // Enable healthchecks for an single endpoint
            app.UseHealthChecks("/healthcheck", healthCheckOptions);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// UseHealthCheck
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static void UseHealthCheck(this IApplicationBuilder app)
        {
            var healthCheckOptions = new HealthCheckOptions
            {
                ResponseWriter = async(c, r) =>
                {
                    c.Response.ContentType = MediaTypeNames.Application.Json;
                    var result = JsonConvert.SerializeObject(
                        new
                    {
                        checks = r.Entries.Select(e =>
                                                  new
                        {
                            Name         = e.Key,
                            Status       = e.Value.Status.ToString(),
                            Mesage       = e.Value.Exception == null ? null : e.Value.Exception.ToString(),
                            ResponseTime = e.Value.Duration.TotalMilliseconds
                        }),
                        totalResponseTime = r.TotalDuration.TotalMilliseconds
                    });
                    await c.Response.WriteAsync(result);
                }
            };

            app.UseHealthChecks("/health", healthCheckOptions);
        }
Ejemplo n.º 29
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();



            var healthCheckOptions = new HealthCheckOptions
            {
                ResponseWriter = async(c, r) =>
                {
                    c.Response.ContentType = MediaTypeNames.Application.Json;
                    var result = JsonConvert.SerializeObject(
                        new
                    {
                        checks = r.Entries.Select(e =>
                                                  new {
                            description  = e.Key,
                            status       = e.Value.Status.ToString(),
                            responseTime = e.Value.Duration.TotalMilliseconds
                        }),
                        totalResponseTime = r.TotalDuration.TotalMilliseconds
                    });
                    await c.Response.WriteAsync(result);
                }
            };

            app.UseHealthChecks("/hc/ready", healthCheckOptions);

            app.UseHealthChecks("/hc/live", new HealthCheckOptions
            {
                // Exclude all checks and return a 200-Ok.
                Predicate = (_) => false
            });


            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService <FileManagerService>();

                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
                });
            });

            Log.Logger = new LoggerConfiguration()
                         .Enrich.FromLogContext()
                         .Enrich.WithExceptionDetails()
                         .WriteTo.Console()
                         .CreateLogger();
        }
Ejemplo n.º 30
0
        public void Equals_Second_Null_Returns_False()
        {
            var options1 = new HealthCheckOptions();

            var equals = options1.Equals(null);

            Assert.False(equals);
        }
Ejemplo n.º 31
0
        public async Task InitializeAsync()
        {
            await _healthCheckLifetime.InitializeAsync();

            HttpClientFactory  = _healthCheckLifetime.HttpClientFactory;
            HealthCheckOptions = new HealthCheckOptions();
            Port = HealthCheckCoHostedLifetime.Port;
        }
        public void DoesNotHaveToRequireHttps()
        {
            // Arrange
            var options = new HealthCheckOptions
            {
                RequireHttps = false
            };
            var module = new HealthCheckModule(Enumerable.Empty<IChecker>(), options);
            var bootstrapper = new ConfigurableBootstrapper(with =>
            {
                with.Module(module);
            });
            var browser = new Browser(bootstrapper);

            // Act
            var response = browser.Get("/healthcheck", with =>
            {
                with.HttpRequest();
            });

            // Assert
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
        }
        public void BlocksUnauthorizedRequests()
        {
            // Arrange
            var options = new HealthCheckOptions
            {
                AuthorizationCallback = context => Task.FromResult(false)
            };
            var module = new HealthCheckModule(Enumerable.Empty<IChecker>(), options);
            var bootstrapper = new ConfigurableBootstrapper(with =>
            {
                with.Module(module);
            });
            var browser = new Browser(bootstrapper);

            // Act
            var response = browser.Get("/healthcheck", with =>
            {
                with.HttpsRequest();
            });

            // Assert
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized));
        }