.NET 6 - Adding Correlation ID from Middleware to Serilog File in ASP.NET Core Web API

4.2k views Asked by At

I have a .NET 6 based ASP.NET Core Web API. I am using Serilog to log the requests to the file log.

Below is my middleware class,

using AspNet.CorrelationIdGenerator;
using Microsoft.Extensions.Primitives;
using Serilog.Context;

namespace MyService.Middlewares.CorrelationId;

public class CorrelationIdHandler
{
    private readonly RequestDelegate _next;
    private const string _correlationIdHeader = "X-Correlation-Id";

    public CorrelationIdHandler(RequestDelegate next) => _next = next;

    public async Task Invoke(HttpContext context, ICorrelationIdGenerator correlationIdGenerator)
    {
        var correlationId = GetCorrelationId(context, correlationIdGenerator);
        AddCorrelationIdHeaderToResponse(context, correlationId);
        using (LogContext.PushProperty(_correlationIdHeader, correlationId))
        {
            await _next(context);
        }
    }

    private static StringValues GetCorrelationId(HttpContext context, ICorrelationIdGenerator correlationIdGenerator)
    {
        if (context.Request.Headers.TryGetValue(_correlationIdHeader, out var correlationId))
        {
            correlationIdGenerator.Set(correlationId);
            return correlationId;
        }
        else
        {
            return correlationIdGenerator.Get();
        }
    }

    private static void AddCorrelationIdHeaderToResponse(HttpContext context, StringValues correlationId)
        => context.Response.OnStarting(() =>
        {
            context.Response.Headers.Add(_correlationIdHeader, new[] { correlationId.ToString() });
            return Task.CompletedTask;
        });
}

In the Swagger response, I get the following in response headers:

 api-supported-versions: 1.0 
 content-type: application/json; charset=utf-8 
 date: Fri,19 Aug 2022 23:22:03 GMT 
 server: Kestrel 
 x-correlation-id: 1ff3d20e-e8a3-4cb3-a5ab-3b0f3c50b2fc 

But, in the Serilog log file, I am not getting the expected CorrelationId. Log looks like following,

{
  "Timestamp": "2022-08-19T23:22:04.1299119+00:00",
  "Level": "Information",
  "MessageTemplate": "{\"Id\":\"-1\"}",
  "RenderedMessage": "{\"Id\":\"-1\"}",
  "Properties": {
    "MachineName": "VMA",
    "ApplicationName": "MyService",
    "Version": "1.0.0.0",
    "EnvironmentName": "Development",
    "SpanId": "01d9fefb3b3499f4",
    "TraceId": "a6d9a772a7714262de644869a0db09ac",
    "ParentId": "0000000000000000",
    "ActionId": "38911c40-e519-465a-a5df-45cb0b8ddfa5",
    "ActionName": "MyAction",
    "RequestId": "0HMK275AMJ90H:0000000B",
    "RequestPath": "/api/v1/users",
    "ConnectionId": "0HMK275AMJ90H",
    "EventType": "A4522030"
  }
}
0

There are 0 answers