我想使用.NetCore 2.2提供的Healthcheck。它的配置非常简单。
除了使用HealthCheck自定义响应之外,我还使用异常处理程序在ErrorController中自定义异常。
问题是Healthcheck不起作用。如果SQL连接引发任何错误,它将转到错误控制器,而不执行我的自定义响应运行状况检查消息。为简化起见,我仅在此处放置两行代码。我的实际代码有很多注册,例如招摇,自动验证,fluentvalidation等,
public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddHealthChecks()
.AddSqlServer(Configuration["ConnectionStrings:defaultConnection"]);
}
下面是配置代码的一部分,再次为简单起见,我减少了此问题所需的代码。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var healthCheckOptions = new HealthCheckOptions();
healthCheckOptions.ResultStatusCodes[HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable;
healthCheckOptions.ResponseWriter = async (context, report) =>
{
var problemDetails = new ProblemDetails
{
Title = "ProviderUnavailable",
Status = (int)report.Status,
Detail = "Service is down",
Instance = context.TraceIdentifier
};
await context.Response.WriteAsync(JsonConvert.SerializeObject(problemDetails));
};
app.UseHealthChecks("/health", healthCheckOptions);
if (env.IsDevelopment())
{
app.UseExceptionHandler("/error-local-development");
}
else
{
app.UseExceptionHandler("/error");
}
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
}
然后,如果我提供了错误的sql凭据,则会引发以下代码错误。
public async Task<PerilsResponse> GetPerilRatingScoringAsync(PerilsRequest request)
{
using (var connection = new SqlConnection(_connectionString))
{
await connection.OpenAsync();//Exception throws here.
}
}
ErrorController.cs:
[Route("/error-local-development")]
[HttpGet]
[ApiExplorerSettings(IgnoreApi = true)]
public IActionResult ErrorLocalDevelopment([FromServices] IHostingEnvironment webHostEnvironment)
{
var feature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
var ex = feature?.Error;
var isDev = webHostEnvironment.IsDevelopment();
var problemDetails = new ProblemDetails
{
Status = StatusCodes.Status500InternalServerError,
Instance = feature?.Path,
Title = isDev ? $"{ex?.GetType().Name}: {ex?.Message}" : "An error occurred.",
Detail = isDev ? ex?.StackTrace : null,
};
return StatusCode(problemDetails.Status.Value, problemDetails);
}
该异常由中间件ErrorController捕获。我想要的是返回自定义响应,该响应写在未调用的代码的Configure部分中。