Skip to content

Commit

Permalink
Added .net 4.8 with middleware wrapper so we can have IHttpClientBuil…
Browse files Browse the repository at this point in the history
…der added to it.
  • Loading branch information
hartmark committed Apr 2, 2023
1 parent e32d305 commit 1d1baca
Show file tree
Hide file tree
Showing 11 changed files with 324 additions and 48 deletions.
7 changes: 7 additions & 0 deletions CorrelationId.sln
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "net48", "net48", "{0D3CBD88
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Net48MvcSample", "samples\net48\Net48MvcSample\Net48MvcSample.csproj", "{DED5BFD9-29F6-4291-B863-1995C33D686B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CorrelationId.Net48.Tests", "test\CorrelationId.Net48.Tests\CorrelationId.Net48.Tests.csproj", "{A4137EAE-590B-476C-838F-A2D4A45AAE4A}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -62,6 +64,10 @@ Global
{DED5BFD9-29F6-4291-B863-1995C33D686B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DED5BFD9-29F6-4291-B863-1995C33D686B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DED5BFD9-29F6-4291-B863-1995C33D686B}.Release|Any CPU.Build.0 = Release|Any CPU
{A4137EAE-590B-476C-838F-A2D4A45AAE4A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A4137EAE-590B-476C-838F-A2D4A45AAE4A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A4137EAE-590B-476C-838F-A2D4A45AAE4A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A4137EAE-590B-476C-838F-A2D4A45AAE4A}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -74,6 +80,7 @@ Global
{0E2E2678-4DBB-4560-AF0E-86ECAF8D9B6F} = {E28C5481-A68F-44AF-983F-EA127E70621A}
{0D3CBD88-90B9-4364-9DE4-CA1FCC9CB023} = {34C0F65A-8BF2-40DA-B0E7-844930EE2A7B}
{DED5BFD9-29F6-4291-B863-1995C33D686B} = {0D3CBD88-90B9-4364-9DE4-CA1FCC9CB023}
{A4137EAE-590B-476C-838F-A2D4A45AAE4A} = {EAF27B74-0B27-4BEE-9F82-DD5812B21B17}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {C0A37404-C50B-472E-9491-DDE2A4BDA882}
Expand Down
18 changes: 18 additions & 0 deletions samples/net48/Net48MvcSample/Controllers/ValuesController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;

namespace Net48MvcSample.Controllers
{
public class ValuesController : ApiController
{
public IEnumerable<string> Get()
{
var correlationId = HttpContext.Current.Request.Headers["X-Correlation-Id"];
var response = new[] { "value1", "value2", correlationId };
return response;
}
}
}

This file was deleted.

5 changes: 2 additions & 3 deletions samples/net48/Net48MvcSample/Net48MvcSample.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,11 @@
</ItemGroup>
<ItemGroup>
<Compile Include="App_Start\WebApiConfig.cs" />
<Compile Include="Controllers\WeatherForecastController.cs" />
<Compile Include="Controllers\ValuesController.cs" />
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="WeatherForecast.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="Global.asax" />
Expand Down Expand Up @@ -162,7 +161,7 @@
<AutoAssignPort>True</AutoAssignPort>
<DevelopmentServerPort>5000</DevelopmentServerPort>
<DevelopmentServerVPath>/</DevelopmentServerVPath>
<IISUrl>http://localhost:5000/</IISUrl>
<IISUrl>http://localhost:31488/</IISUrl>
<NTLMAuthentication>False</NTLMAuthentication>
<UseCustomServer>False</UseCustomServer>
<CustomServerUrl />
Expand Down
20 changes: 0 additions & 20 deletions samples/net48/Net48MvcSample/WeatherForecast.cs

This file was deleted.

108 changes: 108 additions & 0 deletions test/CorrelationId.Net48.Tests/CorrelationId.Net48.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{A4137EAE-590B-476C-838F-A2D4A45AAE4A}</ProjectGuid>
<ProjectTypeGuids>{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CorrelationId.Net48.Tests</RootNamespace>
<AssemblyName>CorrelationId.Net48.Tests</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.ComponentModel.Composition" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Numerics" />
<Reference Include="System.Web" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CorrelationIdMiddlewareWrapper.cs" />
<Compile Include="CorrelationIdServiceCollectionExtensions.cs" />
<Compile Include="HttpClientBuilderTests.cs" />
<Compile Include="INet48MvcSampleApiClient.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\CorrelationId\CorrelationId.csproj">
<Project>{865886fc-ebbe-49e1-8f49-fecd0408ef6e}</Project>
<Name>CorrelationId</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http" Version="2.2.2" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Features" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.WebUtilities" Version="2.2.0" />
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.ObjectPool" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Options" Version="7.0.1" />
<PackageReference Include="Microsoft.Extensions.Primitives" Version="7.0.0" />
<PackageReference Include="Microsoft.Net.Http.Headers" Version="2.2.0" />
<PackageReference Include="Refit" Version="6.3.2" />
<PackageReference Include="Refit.HttpClientFactory" Version="6.3.2" />
<PackageReference Include="System.Buffers" Version="4.5.1" />
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="7.0.0" />
<PackageReference Include="System.IO" Version="4.3.0" />
<PackageReference Include="System.Memory" Version="4.5.5" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
<PackageReference Include="System.Net.Http.Json" Version="6.0.0" />
<PackageReference Include="System.Numerics.Vectors" Version="4.5.0" />
<PackageReference Include="System.Runtime" Version="4.3.0" />
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" Version="6.0.0" />
<PackageReference Include="System.Security.Cryptography.Algorithms" Version="4.3.0" />
<PackageReference Include="System.Security.Cryptography.Encoding" Version="4.3.0" />
<PackageReference Include="System.Security.Cryptography.Primitives" Version="4.3.0" />
<PackageReference Include="System.Security.Cryptography.X509Certificates" Version="4.3.0" />
<PackageReference Include="System.Text.Encodings.Web" Version="6.0.0" />
<PackageReference Include="System.Text.Json" Version="6.0.1" />
<PackageReference Include="System.Threading.Tasks.Extensions" Version="4.5.4" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
<PackageReference Include="xunit" Version="2.1.0" />
<PackageReference Include="xunit.abstractions" Version="2.0.0" />
<PackageReference Include="xunit.assert" Version="2.1.0" />
<PackageReference Include="xunit.core" Version="2.1.0" />
<PackageReference Include="xunit.extensibility.core" Version="2.1.0" />
<PackageReference Include="xunit.extensibility.execution" Version="2.1.0" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
73 changes: 73 additions & 0 deletions test/CorrelationId.Net48.Tests/CorrelationIdMiddlewareWrapper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using CorrelationId.Abstractions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;

namespace CorrelationId.Net48.Tests
{
/// <summary>
/// We don't have any middleware in .net framework so we wrap it in a HttpMessageHandler instead
/// </summary>
public class CorrelationIdMiddlewareWrapper : DelegatingHandler
{
private readonly CorrelationIdMiddleware _correlationIdMiddleware;
private readonly ICorrelationContextFactory _correlationContextFactory;
private readonly IOptions<CorrelationIdOptions> _correlationIdOptions;

public CorrelationIdMiddlewareWrapper(CorrelationIdMiddleware correlationIdMiddleware,
ICorrelationContextFactory correlationContextFactory, IOptions<CorrelationIdOptions> correlationIdOptions)
{
_correlationIdMiddleware = correlationIdMiddleware;
_correlationContextFactory = correlationContextFactory;
_correlationIdOptions = correlationIdOptions;
}

protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var httpContext = GetHttpContext();
await _correlationIdMiddleware.Invoke(httpContext, _correlationContextFactory);

var correlationIds =
httpContext.Request.Headers[_correlationIdOptions.Value.RequestHeader];

foreach (var correlationId in correlationIds)
{
request.Headers.Add(_correlationIdOptions.Value.RequestHeader, correlationId);
}

var response = await base.SendAsync(request, cancellationToken);
return response;
}

private HttpContext GetHttpContext()
{
var httpContext = new DefaultHttpContext();

if (System.Web.HttpContext.Current == null)
{
return httpContext;
}

var correlationIds =
System.Web.HttpContext.Current.Request.Headers
.GetValues(_correlationIdOptions.Value.RequestHeader);

if (correlationIds == null)
{
return httpContext;
}

foreach (var correlationId in correlationIds)
{
httpContext.Request.Headers
.Add(_correlationIdOptions.Value.RequestHeader, correlationId);
}

return httpContext;
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using System.Threading.Tasks;
using CorrelationId.Abstractions;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace CorrelationId.Net48.Tests
{
public static class CorrelationIdServiceCollectionExtensions
{
public static void AddCorrelationIdToHttpClientBuilder(this ServiceCollection serviceCollection, IHttpClientBuilder httpClientBuilder)
{
serviceCollection.AddTransient(x =>
{
return new CorrelationIdMiddleware(
next =>
{
var correlationContextAccessor = x.GetService<ICorrelationContextAccessor>();
// copied from CorrelationId.HttpClient.CorrelationIdHandler
if (!string.IsNullOrEmpty(correlationContextAccessor?.CorrelationContext?.CorrelationId) &&
!next.Request.Headers.ContainsKey(correlationContextAccessor.CorrelationContext.Header))
{
next.Request.Headers.Add(correlationContextAccessor.CorrelationContext.Header,
correlationContextAccessor.CorrelationContext.CorrelationId);
}
return Task.CompletedTask;
},
x.GetService<ILogger<CorrelationIdMiddleware>>(),
x.GetService<IOptions<CorrelationIdOptions>>(),
x.GetService<ICorrelationIdProvider>());
});

serviceCollection.AddTransient<CorrelationIdMiddlewareWrapper>();
httpClientBuilder.AddHttpMessageHandler<CorrelationIdMiddlewareWrapper>();
}
}
}
Loading

0 comments on commit 1d1baca

Please sign in to comment.