Request header propagation .NET Core App Demo
Request header propagation .NET Core App Demo

Request Header Propagation In .NET Core Web Applications

In this short article, let’s have a look at a simple middleware to propagate the request headers.

Why ?

Application might be interacting with many backend APIs using HttpClient instances. Those instances might require specific request headers to be present in the request. And as we have seen in previous blog posts, those headers can be added via AddHttpClient middleware as shown in below code snippet.

There might be some cases where an application is required to send the incoming request headers to the backend APIs.

There can be three different use cases where request header propagation:

  • Forward header as-is
  • Forward a header with different name
  • Generate a new header or conditionally generate header value

For all such scenarios, header propagation middleware can be used.

How ?

If an application needs to use header propagation middleware, it should refer to a NuGet package Microsoft.AspNetCore.HeaderPropagation. Once this reference is added, the middleware can be configured in application startup as shown below.

I used an .NET Core MVC application to test this. As you can see, below snapshot shows two headers:

  • a new header X-CUSTOM-HEADER is inserted to the outgoing request.
  • Value from User-Agent incoming request header is used for new header X-RENAMED-HEADER
Incoming Request Header Propagation using Middleware

Have you ever came across this scenario where you had to forward the request headers from incoming request to outgoing request ? If yes, how did you implement it ? Let me know your thoughts.

Leave a ReplyCancel reply

This Post Has 2 Comments

  1. Shaun

    I have used header propagation and facing a strange issue. It seems the header propagation or the http client is caching the cookies! Sometimes one user’s request cookies are passed onto request coming from another user. Have you faced such a scenario ?

    1. Manoj Choudhari
      Manoj Choudhari

      I have never faced such situation. May be you can try clearing the cookie collection explicitly from HttpClient while making new API request – if you are sure you do not require any cookies to be forwarded. Hope this helps you.