You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 7 Worker Service中如何基于IHost配置自定义健康检查?

.NET 7 Worker Service 健康检查配置方案

问题背景

之前在Worker Service中通过WebApplication方式实现健康检查的代码如下(简化版):

var options = new WebApplicationOptions {
    Args = args, 
    ContentRootPath = WindowsServiceHelpers.IsWindowsService() 
        ? AppContext.BaseDirectory 
        : default
};

var builder = WebApplication.CreateBuilder(options);

builder.Host.UseWindowsService();

builder.Services.AddHealthChecks().AddCheck<ServiceIsOnlineCheck>(nameof(ServiceIsOnlineCheck));
builder.Services.AddHostedService<Worker>();

var healthcheckoptions = new HealthCheckOptions
{
    ResponseWriter = ResponseWriters.WriteDetailedStatus,
    ResultStatusCodes =
            {
                [HealthStatus.Healthy] = StatusCodes.Status200OK,
                [HealthStatus.Degraded] = StatusCodes.Status200OK,
                [HealthStatus.Unhealthy] = StatusCodes.Status200OK
            }
};

var app = builder.Build();
app.UseHealthChecks("/health", healthcheckoptions);

app.Run();

但创建.NET 7新Worker Service时,Program.cs采用Host.CreateDefaultBuilder结构,不清楚如何配置健康检查(需设置自定义响应写入器及其他自定义选项),原代码结构如下:

IHost host = Host.CreateDefaultBuilder(args)
    .UseWindowsService(options =>
    {
        options.ServiceName = "Service Name";
    })
    .ConfigureWebHost(host =>
    {
        // ???
    })
    .ConfigureServices(services =>
    {
        services.AddHostedService<RunOnScheduleWorker>();
    })
    .Build();

host.Run();

完整配置代码

直接在ConfigureWebHost中完成Web中间件配置,同时在ConfigureServices中注册健康检查服务,修改后的完整代码如下:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;

IHost host = Host.CreateDefaultBuilder(args)
    .UseWindowsService(options =>
    {
        options.ServiceName = "Service Name";
    })
    .ConfigureWebHost(webBuilder =>
    {
        // 配置Web服务器及中间件
        webBuilder.Configure(app =>
        {
            // 定义健康检查自定义配置
            var healthCheckOptions = new HealthCheckOptions
            {
                ResponseWriter = ResponseWriters.WriteDetailedStatus,
                ResultStatusCodes =
                {
                    [HealthStatus.Healthy] = StatusCodes.Status200OK,
                    [HealthStatus.Degraded] = StatusCodes.Status200OK,
                    [HealthStatus.Unhealthy] = StatusCodes.Status200OK
                }
            };
            // 挂载健康检查端点
            app.UseHealthChecks("/health", healthCheckOptions);
        });
    })
    .ConfigureServices(services =>
    {
        // 注册健康检查服务及自定义检查项
        services.AddHealthChecks()
                .AddCheck<ServiceIsOnlineCheck>(nameof(ServiceIsOnlineCheck));
        
        services.AddHostedService<RunOnScheduleWorker>();
    })
    .Build();

host.Run();

关键配置说明

  • 注册健康检查服务:在ConfigureServices中通过AddHealthChecks()添加基础健康检查服务,再通过AddCheck加入自定义的ServiceIsOnlineCheck检查项。
  • 配置健康检查中间件:在ConfigureWebHost的Configure方法中,创建HealthCheckOptions实例,设置自定义响应写入器和状态码映射规则,最后通过UseHealthChecks将健康检查端点挂载到/health路径。
  • Windows服务配置:保留原有的UseWindowsService配置,设置自定义服务名称。

可选优化:拆分配置逻辑

如果需要将配置逻辑拆分解耦,可以把HealthCheckOptions注册为单例服务,再在中间件配置中获取使用:

// 在ConfigureServices中注册健康检查配置
services.AddSingleton(new HealthCheckOptions
{
    ResponseWriter = ResponseWriters.WriteDetailedStatus,
    ResultStatusCodes =
    {
        [HealthStatus.Healthy] = StatusCodes.Status200OK,
        [HealthStatus.Degraded] = StatusCodes.Status200OK,
        [HealthStatus.Unhealthy] = StatusCodes.Status200OK
    }
});

// 在ConfigureWebHost的Configure中使用配置
webBuilder.Configure((context, app) =>
{
    var healthCheckOptions = context.Services.GetRequiredService<HealthCheckOptions>();
    app.UseHealthChecks("/health", healthCheckOptions);
});

内容的提问来源于stack exchange,提问作者Henrik Fransas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 06:40:20