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

如何在Azure Durable Functions v4(.NET6)中通过Startup添加关联ID中间件

在Azure Durable Functions v4(.NET 6)中用Startup类实现关联ID追踪

针对你的需求,不用依赖Program.cs,直接在现有Startup类里就能完成关联ID的提取、日志注入和出站请求附加,具体实现步骤如下:

1. 编写自定义关联ID中间件

创建中间件类,负责从Http请求中提取或生成关联ID,并将其注入到日志作用域:

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System.Collections.Generic;
using System.Threading.Tasks;

public class CorrelationIdMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<CorrelationIdMiddleware> _logger;
    public const string CorrelationIdHeader = "X-Correlation-ID";

    public CorrelationIdMiddleware(RequestDelegate next, ILogger<CorrelationIdMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // 从请求头获取关联ID,无则生成新的GUID
        var correlationId = context.Request.Headers.TryGetValue(CorrelationIdHeader, out var headerValue) 
            ? headerValue.ToString() 
            : System.Guid.NewGuid().ToString();

        // 将关联ID存入请求上下文,方便后续调用
        context.Items["CorrelationId"] = correlationId;

        // 加入日志作用域,让Application Insights自动捕获该字段
        using (_logger.BeginScope(new Dictionary<string, object> { { "CorrelationId", correlationId } }))
        {
            // 把关联ID返回给响应头,方便客户端确认
            context.Response.Headers.Append(CorrelationIdHeader, correlationId);
            await _next(context);
        }
    }
}

2. 编写HttpClient消息处理程序

实现自动给所有出站Http请求附加关联ID的逻辑:

using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

public class CorrelationIdMessageHandler : DelegatingHandler
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public CorrelationIdMessageHandler(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        if (_httpContextAccessor.HttpContext?.Items.TryGetValue("CorrelationId", out var correlationId) == true)
        {
            request.Headers.Add(CorrelationIdMiddleware.CorrelationIdHeader, correlationId.ToString());
        }

        return await base.SendAsync(request, cancellationToken);
    }
}

3. 修改Startup类注册服务与中间件

在你的Startup类中,完成中间件、上下文访问器和HttpClient的配置:

using Microsoft.Azure.Functions.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;

[assembly: FunctionsStartup(typeof(YourNamespace.Startup))]
namespace YourNamespace
{
    public class Startup : FunctionsStartup
    {
        public override void Configure(IFunctionsHostBuilder builder)
        {
            // 注册Http上下文访问器,用于获取当前请求的关联ID
            builder.Services.AddHttpContextAccessor();

            // 注册关联ID中间件,并添加到Http管道
            builder.Services.AddTransient<CorrelationIdMiddleware>();
            builder.Services.AddMvc(options =>
            {
                options.UseMiddleware<CorrelationIdMiddleware>();
            });

            // 配置HttpClient,自动附加关联ID到出站请求
            // 可注册命名客户端或全局客户端
            builder.Services.AddHttpClient("CorrelatedClient")
                .AddHttpMessageHandler<CorrelationIdMessageHandler>();

            builder.Services.AddHttpClient()
                .AddHttpMessageHandler<CorrelationIdMessageHandler>();

            builder.Services.AddLogging();
        }
    }
}

效果验证

  • HttpTrigger接收到请求时,中间件会提取或生成X-Correlation-ID,该ID会自动出现在Application Insights的所有日志条目中
  • 使用注册的HttpClient调用其他Azure Functions时,请求头会自动带上X-Correlation-ID,下游函数的日志可通过该ID实现跨服务请求追踪

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 11:46:02