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.