Today I show you how to add header propagation in ASP net.
“Header what?” I hear you say.
Essentially it’s a mechanism whereby when you make Http requests via a HttpClient, you can automatically ‘forward’ headers that were issued to your endpoint.
HeaderX that is passed to an ASP net endpoint gets added to out going http requests via a http client.
HowManually: If we were to do this manually, we would interrogate the http request, find the HeaderX and add it in the outgoing HttpClient request headers.
Propagation:Lets get ASP to do the heavy lifting 1) Add the Microsoft.AspNetCore.HeaderPropagation package
2) Add Header propagation (in Startup.cs or program.cs (minimal api))
3) Use Header Propagation (in Startup.cs or program.cs (minimal api))
4) Create a service that takes HttpClient as a constructor arg
4) Add this AwesomeService to your DI config and set the delegated headers
builder.Services.AddTransient<IAwesomeService, AwesomeService>(); builder.Services.AddHttpClient<IAwesomeService, AwesomeService>(o => o.Timeout = TimeSpan.FromMinutes(1)) .AddHeaderPropagation(o => o.Headers.Add("Header1")); |
Note: this step is only needed with HttpClientFactory, you can see for the IAwesomeService only the “Header1” will be propagated even though we’re configuring Header1 and Header2 in general.
|
5) Testing
One way of testing this is to use Fiddler,
a) Enable the proxy to be seen by .net core
b) Open Fiddler
I find it’s easier to filter on certain hosts
c) Enter the composer and call (execute) your service with some headers
d) Inspect that you receive the Header1
Enjoy! |