受欢迎的博客标签

Health checks in ASP.NET Core

Published

.Net 5.x

step 1:自定义检查控制器和接口

展示数据库的运行状态,他在其验证数据库连接并返回相应的结果

[Route("health")]
        public ActionResult Health()
        {
            using (var connection = new SqlConnection("Server=.;Initial Catalog=master;Integrated Security=true"))
            {
                try
                {
                    connection.Open();
                }
                catch (SqlException)
                {
                    return new StatusCodeResult(503);
               
                }
            }

            return new EmptyResult();
        }

Step 2:

从.NET Core2.2开始,框架本身已经为我们提供了运行状况的检查服务。不需要为运行状态在去自定义检查控制器和接口

Install-Package Microsoft.Extensions.Diagnostics.HealthChecks

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddHealthChecks();
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app
                .UseHealthChecks("/health");
         
        }

 

 

Useful links

https://docs.microsoft.com/zh-cn/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-5.0

https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/health-checks?view=aspnetcore-5.0

https://www.cnblogs.com/yyfh/p/11787434.html

https://rmauro.dev/adding-health-checks-to-net-core-application .net 5.x