Skip to content

Question: How can I read the response body in the EnrichWithHttpResponse method #4254

@shamsipav

Description

@shamsipav

Question

I tried to read the response body in the EnrichWithHttpResponse method in the AddAspNetCoreInstrumentation hook, however httpResponse.Body.CanRead in this case returns false, unlike the httpRequest.Body.CanRead in the EnrichWithHttpRequest method, which is true.

Code example:

            services.AddOpenTelemetry()
                .WithTracing(builder => builder
                    .AddAspNetCoreInstrumentation(o =>
                    {
                        o.EnrichWithHttpRequest = async (activity, httpRequest) =>
                        {
                            // True.
                            if (httpRequest.Body.CanRead)
                            {
                                string requestBody = await new StreamReader(httpRequest.Body).ReadToEndAsync();
                                Console.WriteLine($"requestBody: {requestBody}");
                            }
                        };

                        o.EnrichWithHttpResponse = async (activity, httpResponse) =>
                        {
                            // False.
                            if (httpResponse.Body.CanRead)
                            {
                                string responseBody = await new StreamReader(httpResponse.Body).ReadToEndAsync();
                                Console.WriteLine($"responseBody: {responseBody}");
                            }
                        };
                    })
                    .AddJaegerExporter());

Is there any way to get the body of the response?

Environment

ASP.NET Core 3.1 Web API project

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions