In this short article, let’s have a look at a simple middleware to propagate the request headers.
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.
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-HEADERis inserted to the outgoing request.
- Value from
User-Agentincoming request header is used for new header
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.
This Post Has 2 Comments
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 ?
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.