Skip to content

Is HTTP EnrichWithHttpResponseMessage expected to be executed before all delegate handlers do their job? #2841

Open
@marcinjahn

Description

@marcinjahn

I register an HTTP client in my app, like this:

services.AddHttpClient<MyClient>()
   .ConfigureAdditionalHttpMessageHandlers(
            (handlers, _) => handlers.Add(new MyHandler(options))
        );

My handler:

public class MyHandler(MyHandlerOptions options) : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken
    )
    {
        HttpResponseMessage? response = null;

        try
        {
            response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
        }
        finally
        {
// BREAKPOINT
            if (request.Content is not null && options.AttachRequestBodyPredicate(response))
            {
                var requestBody = await request.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);

                // do something with the body
            }
        }

        return response;
    }
}

I also add tracing:

        services
            .AddOpenTelemetry()
            .WithTracing(cfg =>
            {
                cfg.SetResourceBuilder(resourceBuilder);
                cfg.AddHttpClientInstrumentation(opt =>
                {
                    opt.EnrichWithHttpResponseMessage = (activity, response) => {
// BREAKPOINT
                       // some enrichment
                });

                cfg.AddOtlpExporter(options =>
                {
                    options.Endpoint = new Uri($"http://{tracingConfiguration.Host}:4317");
                });

                cfg.SetErrorStatusOnException();
            });

I set breakpoint within the EnrichWithHttpResponseMessage action and also in my delegate handler. I'd expect the breakpoint in delegate handler to be hit first. However, it's the EnrichWithHttpResponseMessage action that gets hit first.

Why is that?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions