HTTP Header Propogation in ASP.Net Core

.Net core has made it super easy for header propogation, which is to transfer the header information from one http request to subsequent requests along the line, across multiple services. One common use case is to transfer the token information to subsequent services which are called down the line.

Make HTTP requests using IHttpClientFactory in ASP.NET Core | Microsoft Docs

The above link points to the Microsoft documentation and that’s pretty much what’s needed for implement the feature. The only issue I had was, when I tried to implement it, the header value was getting overwritten with the default value in the response.

I wanted the service to just transfer the header info if it was present, and if it was absent, create the header with a new GUID and transfer to services down the line. I tried to write many conditions to achieve the same, but at the end it was just adding both lines together.

services.AddHeaderPropagation(options =>
{
   options.Headers.Add("X-TraceId");
   options.Headers.Add("X-TraceId" , context => {
            return new StringValues(Guid.NewGuid().ToString());
   });
});

When we add both those lines above , the first line helps to transfer the X-TraceId to the next service. If its not present, then the second line kicks in and adds the header along with a new GUID to the next service. This is exactly what I wanted. Problem solved !

Leave a comment

Your email address will not be published. Required fields are marked *