New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
HttpClientFactory Header Propagation MessageHandler #1099
Closed
Closed
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 35 additions & 0 deletions
35
...ttpClientFactory/HeaderPropagation/src/DependencyInjection/HeaderPropagationExtensions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
using System; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.Extensions.DependencyInjection.Extensions; | ||
using Microsoft.Extensions.Http; | ||
using Microsoft.Extensions.Http.HeaderPropagation; | ||
using Microsoft.Extensions.Options; | ||
|
||
namespace Microsoft.Extensions.DependencyInjection | ||
{ | ||
public static class HeaderPropagationExtensions | ||
{ | ||
public static IServiceCollection AddHeaderPropagation(this IServiceCollection services, Action<HeaderPropagationOptions> configure) | ||
{ | ||
services.AddHttpContextAccessor(); | ||
services.Configure(configure); | ||
services.TryAddEnumerable(ServiceDescriptor.Singleton<IHttpMessageHandlerBuilderFilter, HeaderPropagationMessageHandlerBuilderFilter>()); | ||
return services; | ||
} | ||
|
||
public static IHttpClientBuilder AddHeaderPropagation(this IHttpClientBuilder builder, Action<HeaderPropagationOptions> configure) | ||
{ | ||
builder.Services.AddHttpContextAccessor(); | ||
builder.Services.Configure(configure); | ||
builder.AddHttpMessageHandler((sp) => | ||
{ | ||
var options = sp.GetRequiredService<IOptions<HeaderPropagationOptions>>(); | ||
var contextAccessor = sp.GetRequiredService<IHttpContextAccessor>(); | ||
|
||
return new HeaderPropagationMessageHandler(options.Value, contextAccessor); | ||
}); | ||
|
||
return builder; | ||
} | ||
} | ||
} |
16 changes: 16 additions & 0 deletions
16
src/HttpClientFactory/HeaderPropagation/src/HeaderPropagationEntry.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.Extensions.Primitives; | ||
using System; | ||
using System.Net.Http; | ||
|
||
namespace Microsoft.Extensions.Http.HeaderPropagation | ||
{ | ||
public class HeaderPropagationEntry | ||
{ | ||
public string InputName { get; set; } | ||
public string OutputName { get; set; } | ||
public StringValues DefaultValues { get; set; } | ||
public Func<HttpRequestMessage, HttpContext, StringValues> DefaultValuesGenerator { get; set; } | ||
public bool AlwaysAdd { get; set; } | ||
} | ||
} |
54 changes: 54 additions & 0 deletions
54
src/HttpClientFactory/HeaderPropagation/src/HeaderPropagationMessageHandler.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
using System.Net.Http; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.Extensions.Primitives; | ||
|
||
namespace Microsoft.Extensions.Http.HeaderPropagation | ||
{ | ||
public class HeaderPropagationMessageHandler : DelegatingHandler | ||
{ | ||
private readonly HeaderPropagationOptions _options; | ||
private readonly IHttpContextAccessor _contextAccessor; | ||
|
||
public HeaderPropagationMessageHandler(HeaderPropagationOptions options, IHttpContextAccessor contextAccessor) | ||
{ | ||
_options = options; | ||
_contextAccessor = contextAccessor; | ||
} | ||
|
||
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | ||
{ | ||
if (_contextAccessor.HttpContext != null) | ||
{ | ||
foreach (var header in _options.Headers) | ||
{ | ||
if (!_contextAccessor.HttpContext.Request.Headers.TryGetValue(header.InputName, out var values) | ||
|| StringValues.IsNullOrEmpty(values)) | ||
{ | ||
if (header.DefaultValuesGenerator != null) | ||
{ | ||
values = header.DefaultValuesGenerator(request, _contextAccessor.HttpContext); | ||
if (StringValues.IsNullOrEmpty(values)) continue; | ||
} | ||
else if (!StringValues.IsNullOrEmpty(header.DefaultValues)) | ||
{ | ||
values = header.DefaultValues; | ||
} | ||
else | ||
{ | ||
continue; | ||
} | ||
} | ||
|
||
if (header.AlwaysAdd || !request.Headers.Contains(header.OutputName)) | ||
{ | ||
request.Headers.TryAddWithoutValidation(header.OutputName, (string[])values); | ||
} | ||
} | ||
} | ||
|
||
return base.SendAsync(request, cancellationToken); | ||
} | ||
} | ||
} |
27 changes: 27 additions & 0 deletions
27
src/HttpClientFactory/HeaderPropagation/src/HeaderPropagationMessageHandlerBuilderFilter.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
using System; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.Extensions.Options; | ||
|
||
namespace Microsoft.Extensions.Http.HeaderPropagation | ||
{ | ||
internal class HeaderPropagationMessageHandlerBuilderFilter : IHttpMessageHandlerBuilderFilter | ||
{ | ||
private readonly HeaderPropagationOptions _options; | ||
private readonly IHttpContextAccessor _contextAccessor; | ||
|
||
public HeaderPropagationMessageHandlerBuilderFilter(IOptions<HeaderPropagationOptions> options, IHttpContextAccessor contextAccessor) | ||
{ | ||
_options = options.Value; | ||
_contextAccessor = contextAccessor; | ||
} | ||
|
||
public Action<HttpMessageHandlerBuilder> Configure(Action<HttpMessageHandlerBuilder> next) | ||
{ | ||
return builder => | ||
{ | ||
builder.AdditionalHandlers.Add(new HeaderPropagationMessageHandler(_options, _contextAccessor)); | ||
next(builder); | ||
}; | ||
} | ||
} | ||
} |
9 changes: 9 additions & 0 deletions
9
src/HttpClientFactory/HeaderPropagation/src/HeaderPropagationOptions.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
using System.Collections.Generic; | ||
|
||
namespace Microsoft.Extensions.Http.HeaderPropagation | ||
{ | ||
public class HeaderPropagationOptions | ||
{ | ||
public IList<HeaderPropagationEntry> Headers { get; set; } = new List<HeaderPropagationEntry>(); | ||
} | ||
} |
26 changes: 26 additions & 0 deletions
26
...ttpClientFactory/HeaderPropagation/src/Microsoft.Extensions.Http.HeaderPropagation.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<Description> | ||
The HttpClient factory is a pattern for configuring and retrieving named HttpClients in a composable way. This package add to IHttpClientFactory to propagating headers from the current request to an outgoing http request. | ||
</Description> | ||
<TargetFramework>netstandard2.0</TargetFramework> | ||
<NoWarn>$(NoWarn);CS1591</NoWarn> | ||
<GenerateDocumentationFile>true</GenerateDocumentationFile> | ||
<PackageTags>aspnetcore;httpclient</PackageTags> | ||
|
||
<RootNamespace>Microsoft.Extensions.Http.HeaderPropagation</RootNamespace> | ||
<IsShipping>true</IsShipping> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<InternalsVisibleTo Include="Microsoft.Extensions.Http.HeaderPropagation.Tests" /> | ||
</ItemGroup> | ||
|
||
<ItemGroup> | ||
<Reference Include="Microsoft.AspNetCore.Http" /> | ||
<Reference Include="Microsoft.Extensions.Http" /> | ||
<Reference Include="Microsoft.Extensions.DependencyInjection" /> | ||
</ItemGroup> | ||
|
||
</Project> |
12 changes: 12 additions & 0 deletions
12
...ientFactory/HeaderPropagation/test/HeaderPropagation.Tests/HeaderPropagation.Tests.csproj
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFrameworks>netcoreapp3.0;net472</TargetFrameworks> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<Reference Include="Microsoft.Extensions.DependencyInjection" /> | ||
<Reference Include="Microsoft.Extensions.Http.HeaderPropagation" /> | ||
</ItemGroup> | ||
|
||
</Project> |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@davidfowl we've run into trouble trying to use IHttpContextAccessor in DelegatingHandlers before haven't we? People would run their HttpClient requests in parallel and cause unsafe mulithreaded access to HttpContext. When ApplicationInsights dealt with a similar problem they concluded the best way to handle it was to collect fields they needed up front and pass them through in a dedicated data structure.
What if instead of a DelegatingHandler we provided a set of request composition helpers on top of HttpClient and HttpRequestMessage?
The biggest downside I can see would be the caller needing to be HttpContext aware, which may or may not work for various libraries.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi Chris,
yes the HttpContext is not thread-safe and it's a really valid point, not sure why I haven't considered sending requests in parallel :(
I should add a
HeaderPropagationInitializer
similar to theTelemetryInitializer
that get the required values from the context and store it in it's own data structure. However this will mean that it needs to be aware of all the headers forwarded by all theHttpClient
s as we will want to lock on the context only once per MVC request. I'll have to think about it.About the composition helpers, I'm not sure how that will fit with the
HttpClientFactory
. Can you elaborate a bit more on what you have in mind?Btw here is the issue you are referring to:
https://github.com/Microsoft/ApplicationInsights-aspnetcore/issues/373
I remembered he mentioned it on last year talk at NDC :)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The composition helpers wouldn't be affiliated with HttpClientFactory, they'd be APIs for directly creating or operating on HttpRequestMessages before calling into HttpClient. They may have extensions on HttpClient to facilitate.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yeah, I think the right thing to do here is to make a middleware that initializes state, and a standalone
DelegatingHandler
that reads that state to modify the outgoing request.I don't think we need to tie this to the http client factory. In general library code doesn't need to integrate with it directly because wiring up a
DelegatingHandler
is easy.