我已在我的应用中启用.NET Health Checks
。我给支票起一个名字,并根据支票的结果添加一条消息。以下示例显示了名为Test Health Check
的检查,如果返回了健康结果,则会显示消息Server Is Healthy!
。当我访问api端点时,我只会看到Healthy
。在哪里可以查看有关支票的更多详细信息?
.AddCheck("Test Health Check", () => HealthCheckResult.Healthy("Server Is Healthy!"))
答案 0 :(得分:0)
@Fildor的这段youtube视频很有帮助。
这就是我所做的:
在Program.cs中,我添加了:
applicationBuilder.UseEndpoints(endpoints => { endpoints.MapControllers(); endpoints.MapCustomHealthChecks("Health"); });
然后我创建了一个HealthCheckExtensions
类:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mime;
using System.Text;
namespace my.namespace.Features.HealthChecks
{
// a custom response class for the .NET Health Check
public static class HealthCheckExtensions
{
public static IEndpointConventionBuilder MapCustomHealthChecks(
this IEndpointRouteBuilder endpoints, string serviceName)
{
return endpoints.MapHealthChecks("/api/health", new HealthCheckOptions
{
ResponseWriter = async (context, report) =>
{
var result = JsonConvert.SerializeObject(
new HealthResult
{
Name = serviceName,
Status = report.Status.ToString(),
Duration = report.TotalDuration,
Info = report.Entries.Select(e => new HealthInfo
{
Key = e.Key,
Description = e.Value.Description,
Duration = e.Value.Duration,
Status = Enum.GetName(typeof(HealthStatus),
e.Value.Status),
Error = e.Value.Exception?.Message
}).ToList()
}, Formatting.None,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
context.Response.ContentType = MediaTypeNames.Application.Json;
await context.Response.WriteAsync(result);
}
});
}
}
}
HealthInfo
类:
using System;
using System.Collections.Generic;
using System.Text;
namespace my.namespace.Features.HealthChecks
{
public class HealthInfo
{
public string Key { get; set; }
public string Description { get; set; }
public TimeSpan Duration { get; set; }
public string Status { get; set; }
public string Error { get; set; }
}
}
HealthResult
类:
using System;
using System.Collections.Generic;
using System.Text;
namespace my.namespace.Features.HealthChecks
{
public class HealthResult
{
public string Name { get; set; }
public string Status { get; set; }
public TimeSpan Duration { get; set; }
public ICollection<HealthInfo> Info { get; set; }
}
}