I have a .NET 6 Web API project. In a middleware I'm copying "x-correlation-id" header from request to response. When I run, it works ok and I see the x-correlation-id in response headers on client app.
The fragment of Program.cs is below:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpLogging(logging =>
{
logging.LoggingFields = HttpLoggingFields.All;
logging.RequestHeaders.Add("x-correlation-id");
logging.ResponseHeaders.Add("x-correlation-id");
});
var app = builder.Build();
app.Use(async (context, nextMiddleware) =>
{
context.Response.OnStarting(() =>
{
if (context.Response.Headers.ContainsKey("x-correlation-id"))
context.Response.Headers["x-correlation-id"] = "test " context.Request.Headers["x-correlation-id"];
else
context.Response.Headers.Add("x-correlation-id", "test " context.Request.Headers["x-correlation-id"]);
return Task.FromResult(0);
});
await nextMiddleware();
});
app.UseHttpLogging();
I also want this modified response to be logged. I don't see this added header in logs generated by app.UseHttpLogging()
line. When I add this header in controller such as Response.Headers["x-correlation-id"] = "test";
I can see that field logging.
How can I log this modified http response?
CodePudding user response:
HttpLoggingMiddleware
processes response headers before it starts executing the response body, so you can work around by setting the header in the middleware, not in the OnStarting
call:
app.Use(async (context, nextMiddleware) =>
{
if (context.Response.Headers.ContainsKey("x-correlation-id"))
context.Response.Headers["x-correlation-id"] = "test " context.Request.Headers["x-correlation-id"];
else
context.Response.Headers.Add("x-correlation-id", "test " context.Request.Headers["x-correlation-id"]);
await nextMiddleware();
});
app.UseHttpLogging();
Another option - write your own middleware which will log the response headers after the response has started.