├── donate2laojiu.png ├── HttpMessageHandlerFactory.Polly ├── PollyHttpMessageHandlerBuilderExtensions.cs └── HttpMessageHandlerFactory.Polly.csproj ├── HttpMessageHandlerFactory ├── Implementations │ ├── NameRegistration.cs │ ├── NameProxy.cs │ ├── LifetimeHttpHandler.cs │ ├── NonCapturingTimer.cs │ ├── ExpiredHandlerEntry.cs │ ├── ActiveHandlerEntry.cs │ ├── HttpMessageHandlerBuilder.cs │ ├── DefaultHttpMessageHandlerFactory.cs │ └── ExpiredHandlerEntryCleaner.cs ├── DependencyInjection │ ├── IHttpMessageHandlerBuilder.cs │ ├── ServiceCollectionExtensions.cs │ └── HttpMessageHandlerBuilderExtensions.cs ├── HttpMessageHandlerFactory.csproj ├── IHttpMessageHandlerFactory.cs ├── HttpMessageHandlerOptions.cs ├── HttpMessageHandlerFactoryExtensions.cs └── CookieHttpHandler.cs ├── ConsoleApp ├── ConsoleApp.csproj ├── AppHttpHandler.cs └── Program.cs ├── Directory.Build.props ├── LICENSE ├── HttpMessageHandlerFactory.sln ├── .gitattributes ├── README.md └── .gitignore /donate2laojiu.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xljiulang/HttpMessageHandlerFactory/HEAD/donate2laojiu.png -------------------------------------------------------------------------------- /HttpMessageHandlerFactory.Polly/PollyHttpMessageHandlerBuilderExtensions.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xljiulang/HttpMessageHandlerFactory/HEAD/HttpMessageHandlerFactory.Polly/PollyHttpMessageHandlerBuilderExtensions.cs -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/Implementations/NameRegistration.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | 3 | namespace HttpMessageHandlerFactory.Implementations 4 | { 5 | /// 6 | /// 别登记 7 | /// 8 | sealed class NameRegistration : HashSet 9 | { 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/Implementations/NameProxy.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace HttpMessageHandlerFactory.Implementations 4 | { 5 | /// 6 | /// 别名和代理 7 | /// 8 | /// 别名 9 | /// 支持携带UserInfo的代理地址 10 | sealed record NameProxy(string Name, Uri? ProxyUri); 11 | } 12 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/DependencyInjection/IHttpMessageHandlerBuilder.cs: -------------------------------------------------------------------------------- 1 | namespace Microsoft.Extensions.DependencyInjection 2 | { 3 | /// 4 | /// Http消息处理者创建者 5 | /// 6 | public interface IHttpMessageHandlerBuilder 7 | { 8 | /// 9 | /// 选项名 10 | /// 11 | string Name { get; } 12 | 13 | /// 14 | /// 服务集合 15 | /// 16 | IServiceCollection Services { get; } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/HttpMessageHandlerFactory.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | HttpMessageHandlerFactory 5 | 具有生命周期管理和动态Web代理的HttpMessageHandler创建工厂 6 | $(TargetPath)\$(AssemblyName).xml 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /ConsoleApp/ConsoleApp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net6.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/IHttpMessageHandlerFactory.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | 4 | namespace HttpMessageHandlerFactory 5 | { 6 | /// 7 | /// Http消息处理者工厂 8 | /// 9 | public interface IHttpMessageHandlerFactory 10 | { 11 | /// 12 | /// 创建用于请求的HttpMessageHandler 13 | /// 14 | /// 别名 15 | /// 支持携带UserInfo的代理地址 16 | /// 17 | HttpMessageHandler CreateHandler(string name, Uri? proxyUri); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Directory.Build.props: -------------------------------------------------------------------------------- 1 | 2 | 3 | 1.0.1 4 | enable 5 | net6.0 6 | true 7 | laojiu 8 | laojiu 9 | $(MSBuildThisFileDirectory)artifacts 10 | true 11 | MIT 12 | https://github.com/xljiulang/HttpMessageHandlerFactory 13 | 14 | 15 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory.Polly/HttpMessageHandlerFactory.Polly.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | HttpMessageHandlerFactory.Polly 5 | 为HttpMessageHandlerFactory提供Polly策略扩展 6 | $(TargetPath)\$(AssemblyName).xml 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/Implementations/LifetimeHttpHandler.cs: -------------------------------------------------------------------------------- 1 | using System.Net.Http; 2 | 3 | namespace HttpMessageHandlerFactory.Implementations 4 | { 5 | /// 6 | /// 表示自主管理生命周期的的HttpMessageHandler 7 | /// 8 | sealed class LifetimeHttpHandler : DelegatingHandler 9 | { 10 | /// 11 | /// 具有生命周期的HttpHandler 12 | /// 13 | /// 14 | public LifetimeHttpHandler(HttpMessageHandler httpHandler) 15 | { 16 | this.InnerHandler = httpHandler; 17 | } 18 | 19 | /// 20 | /// 这里不释放资源 21 | /// 22 | /// 23 | protected override void Dispose(bool disposing) 24 | { 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ConsoleApp/AppHttpHandler.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using Microsoft.Extensions.Logging.Abstractions; 3 | using System.Net.Http; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace ConsoleApp 8 | { 9 | sealed class AppHttpHandler : DelegatingHandler 10 | { 11 | private readonly ILogger logger; 12 | 13 | public AppHttpHandler() 14 | : this(NullLogger.Instance) 15 | { 16 | } 17 | 18 | public AppHttpHandler(ILogger logger) 19 | { 20 | this.logger = logger; 21 | } 22 | 23 | protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 24 | { 25 | this.logger.LogInformation($"App开始请求{request.RequestUri}"); 26 | var response = await base.SendAsync(request, cancellationToken); 27 | 28 | this.logger.LogInformation($"App请求{request.RequestUri}完成"); 29 | return response; 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /ConsoleApp/Program.cs: -------------------------------------------------------------------------------- 1 | using HttpMessageHandlerFactory; 2 | using Microsoft.Extensions.DependencyInjection; 3 | using Microsoft.Extensions.Logging; 4 | using System; 5 | using System.Threading.Tasks; 6 | 7 | namespace ConsoleApp 8 | { 9 | class Program 10 | { 11 | static async Task Main(string[] args) 12 | { 13 | var services = new ServiceCollection(); 14 | services.AddLogging(x => x.AddConsole()); 15 | services.AddHttpMessageHandlerFactory("App") 16 | .AddHttpMessageHandler() 17 | .SetHandlerLifetime(TimeSpan.FromMinutes(1d)); 18 | 19 | var serviceProvider = services.BuildServiceProvider(); 20 | var factory = serviceProvider.GetRequiredService(); 21 | 22 | var proxyUri = default(Uri); 23 | var httpClient = factory.CreateClient("App", proxyUri); 24 | var html = await httpClient.GetStringAsync("https://github.com/xljiulang/HttpMessageHandlerFactory/blob/master/README.md"); 25 | Console.WriteLine(html); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/HttpMessageHandlerOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net.Http; 4 | 5 | namespace HttpMessageHandlerFactory 6 | { 7 | /// 8 | /// HttpMessageHandler选项 9 | /// 10 | public class HttpMessageHandlerOptions 11 | { 12 | /// 13 | /// 获取或设置生命周期 14 | /// 默认两分钟 15 | /// 16 | public TimeSpan Lifetime { get; set; } = TimeSpan.FromMinutes(2d); 17 | 18 | /// 19 | /// 获取属性记录字典 20 | /// 21 | public Dictionary Properties { get; set; } = new(); 22 | 23 | /// 24 | /// 获取额外的创建委托 25 | /// 26 | public List> AdditionalHandlers { get; } = new(); 27 | 28 | /// 29 | /// 获取基础的配置委托 30 | /// 31 | public List> PrimaryHandlerConfigures { get; } = new(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 老九 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/Implementations/NonCapturingTimer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | 4 | namespace HttpMessageHandlerFactory.Implementations 5 | { 6 | static class NonCapturingTimer 7 | { 8 | public static Timer Create(TimerCallback callback, object state, TimeSpan dueTime, TimeSpan period) 9 | { 10 | if (callback is null) 11 | { 12 | throw new ArgumentNullException(nameof(callback)); 13 | } 14 | 15 | // Don't capture the current ExecutionContext and its AsyncLocals onto the timer 16 | bool restoreFlow = false; 17 | try 18 | { 19 | if (!ExecutionContext.IsFlowSuppressed()) 20 | { 21 | ExecutionContext.SuppressFlow(); 22 | restoreFlow = true; 23 | } 24 | 25 | return new Timer(callback, state, dueTime, period); 26 | } 27 | finally 28 | { 29 | // Restore the current ExecutionContext 30 | if (restoreFlow) 31 | { 32 | ExecutionContext.RestoreFlow(); 33 | } 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/Implementations/ExpiredHandlerEntry.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using System; 3 | using System.Net.Http; 4 | 5 | namespace HttpMessageHandlerFactory.Implementations 6 | { 7 | /// 8 | /// 已过期的条目 9 | /// https://github.com/dotnet/runtime/blob/v7.0.0/src/libraries/Microsoft.Extensions.Http/src/ExpiredHandlerTrackingEntry.cs 10 | /// 11 | sealed class ExpiredHandlerEntry 12 | { 13 | private readonly WeakReference livenessTracker; 14 | 15 | public bool CanDispose => !livenessTracker.IsAlive; 16 | 17 | public NameProxy NameProxy { get; } 18 | 19 | public IServiceScope ServiceScope { get; } 20 | 21 | /// 22 | /// LifetimeHttpHandler的InnerHandler 23 | /// 24 | public HttpMessageHandler InnerHandler { get; } 25 | 26 | /// 27 | /// 已过期的条目 28 | /// 这里不要引用entry.LifetimeHttpHandler 29 | /// 30 | /// 31 | public ExpiredHandlerEntry(ActiveHandlerEntry entry) 32 | { 33 | this.NameProxy = entry.NameProxy; 34 | this.ServiceScope = entry.ServiceScope; 35 | 36 | this.livenessTracker = new WeakReference(entry.LifetimeHttpHandler); 37 | this.InnerHandler = entry.LifetimeHttpHandler.InnerHandler!; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/HttpMessageHandlerFactoryExtensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Http; 4 | 5 | namespace HttpMessageHandlerFactory 6 | { 7 | /// 8 | /// HttpMessageHandlerFactory扩展 9 | /// 10 | public static class HttpMessageHandlerFactoryExtensions 11 | { 12 | /// 13 | /// 创建Http客户端 14 | /// 15 | /// 16 | /// 别名 17 | /// 支持携带UserInfo的代理地址 18 | /// cookie容器 19 | /// 20 | public static HttpClient CreateClient(this IHttpMessageHandlerFactory factory, string name, Uri? proxyUri = null, CookieContainer? cookieContainer = null) 21 | { 22 | var httpHandler = factory.CreateHandler(name, proxyUri, cookieContainer); 23 | return new HttpClient(httpHandler, disposeHandler: false); 24 | } 25 | 26 | /// 27 | /// 创建Http执行器 28 | /// 29 | /// 30 | /// 别名 31 | /// 支持携带UserInfo的代理地址 32 | /// cookie容器 33 | /// 34 | public static HttpMessageInvoker CreateInvoker(this IHttpMessageHandlerFactory factory, string name, Uri? proxyUri = null, CookieContainer? cookieContainer = null) 35 | { 36 | var httpHandler = factory.CreateHandler(name, proxyUri, cookieContainer); 37 | return new HttpMessageInvoker(httpHandler, disposeHandler: false); 38 | } 39 | 40 | private static HttpMessageHandler CreateHandler(this IHttpMessageHandlerFactory factory, string name, Uri? proxyUri, CookieContainer? cookieContainer) 41 | { 42 | var httpHandler = factory.CreateHandler(name, proxyUri); 43 | if (cookieContainer != null) 44 | { 45 | httpHandler = new CookieHttpHandler(httpHandler, cookieContainer); 46 | } 47 | return httpHandler; 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.6.33513.286 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HttpMessageHandlerFactory", "HttpMessageHandlerFactory\HttpMessageHandlerFactory.csproj", "{224A16FC-7B8B-45C3-9A3B-0563BCD939B6}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ConsoleApp", "ConsoleApp\ConsoleApp.csproj", "{63603F3F-75E5-4EC6-8F27-87E9BBCFB565}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "HttpMessageHandlerFactory.Polly", "HttpMessageHandlerFactory.Polly\HttpMessageHandlerFactory.Polly.csproj", "{C89E0481-C61E-4502-911B-0EB1A4439FC0}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {224A16FC-7B8B-45C3-9A3B-0563BCD939B6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {224A16FC-7B8B-45C3-9A3B-0563BCD939B6}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {224A16FC-7B8B-45C3-9A3B-0563BCD939B6}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {224A16FC-7B8B-45C3-9A3B-0563BCD939B6}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {63603F3F-75E5-4EC6-8F27-87E9BBCFB565}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {63603F3F-75E5-4EC6-8F27-87E9BBCFB565}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {63603F3F-75E5-4EC6-8F27-87E9BBCFB565}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {63603F3F-75E5-4EC6-8F27-87E9BBCFB565}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {C89E0481-C61E-4502-911B-0EB1A4439FC0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {C89E0481-C61E-4502-911B-0EB1A4439FC0}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {C89E0481-C61E-4502-911B-0EB1A4439FC0}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {C89E0481-C61E-4502-911B-0EB1A4439FC0}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {C87A8A28-D37B-4963-A546-D4428013A19F} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/DependencyInjection/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using HttpMessageHandlerFactory; 2 | using HttpMessageHandlerFactory.Implementations; 3 | using Microsoft.Extensions.DependencyInjection.Extensions; 4 | using System.Linq; 5 | 6 | namespace Microsoft.Extensions.DependencyInjection 7 | { 8 | /// 9 | /// ServiceCollection扩展 10 | /// 11 | public static class ServiceCollectionExtensions 12 | { 13 | /// 14 | /// 创建别名的HttpMessageHandler的builder 15 | /// 16 | /// 17 | /// 别名 18 | /// 19 | public static IHttpMessageHandlerBuilder AddHttpMessageHandlerFactory(this IServiceCollection services, string name) 20 | { 21 | services.AddHttpMessageHandlerFactory(); 22 | 23 | var descriptor = services.FirstOrDefault(item => item.ServiceType == typeof(NameRegistration)); 24 | var registration = descriptor?.ImplementationInstance as NameRegistration; 25 | registration?.Add(name); 26 | 27 | return new DefaultProxyHttpClientBuilder(name, services); 28 | } 29 | 30 | /// 31 | /// 注册IHttpMessageHandlerFactory服务 32 | /// 33 | /// 34 | /// 35 | public static IServiceCollection AddHttpMessageHandlerFactory(this IServiceCollection services) 36 | { 37 | services.AddOptions(); 38 | services.TryAddSingleton(new NameRegistration()); 39 | services.TryAddTransient(); 40 | services.TryAddSingleton(); 41 | services.TryAddSingleton(); 42 | return services; 43 | } 44 | 45 | 46 | private class DefaultProxyHttpClientBuilder : IHttpMessageHandlerBuilder 47 | { 48 | public string Name { get; } 49 | 50 | public IServiceCollection Services { get; } 51 | 52 | public DefaultProxyHttpClientBuilder(string name, IServiceCollection services) 53 | { 54 | this.Name = name; 55 | this.Services = services; 56 | } 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/Implementations/ActiveHandlerEntry.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using System; 3 | using System.Diagnostics; 4 | using System.Threading; 5 | 6 | namespace HttpMessageHandlerFactory.Implementations 7 | { 8 | /// 9 | /// 活跃的条目 10 | /// https://github.com/dotnet/runtime/blob/v7.0.0/src/libraries/Microsoft.Extensions.Http/src/ActiveHandlerTrackingEntry.cs 11 | /// 12 | sealed class ActiveHandlerEntry 13 | { 14 | private static readonly TimerCallback timerCallback = (s) => ((ActiveHandlerEntry)s!).Timer_Tick(); 15 | 16 | private readonly object root = new(); 17 | private bool timerInitialized = false; 18 | 19 | private Timer? timer; 20 | private TimerCallback? callback; 21 | 22 | public TimeSpan Lifetime { get; } 23 | 24 | public NameProxy NameProxy { get; } 25 | 26 | public IServiceScope ServiceScope { get; } 27 | 28 | public LifetimeHttpHandler LifetimeHttpHandler { get; } 29 | 30 | 31 | public ActiveHandlerEntry( 32 | TimeSpan lifetime, 33 | NameProxy nameProxy, 34 | IServiceScope serviceScope, 35 | LifetimeHttpHandler lifetimeHttpHandler) 36 | { 37 | this.Lifetime = lifetime; 38 | this.NameProxy = nameProxy; 39 | this.ServiceScope = serviceScope; 40 | this.LifetimeHttpHandler = lifetimeHttpHandler; 41 | } 42 | 43 | 44 | public void StartExpiryTimer(TimerCallback callback) 45 | { 46 | if (this.Lifetime == Timeout.InfiniteTimeSpan) 47 | { 48 | return; 49 | } 50 | 51 | if (Volatile.Read(ref this.timerInitialized)) 52 | { 53 | return; 54 | } 55 | 56 | this.StartExpiryTimerSlow(callback); 57 | } 58 | 59 | private void StartExpiryTimerSlow(TimerCallback callback) 60 | { 61 | Debug.Assert(Lifetime != Timeout.InfiniteTimeSpan); 62 | 63 | lock (this.root) 64 | { 65 | if (Volatile.Read(ref this.timerInitialized)) 66 | { 67 | return; 68 | } 69 | 70 | this.callback = callback; 71 | this.timer = NonCapturingTimer.Create(timerCallback, this, Lifetime, Timeout.InfiniteTimeSpan); 72 | this.timerInitialized = true; 73 | } 74 | } 75 | 76 | private void Timer_Tick() 77 | { 78 | Debug.Assert(this.callback != null); 79 | Debug.Assert(this.timer != null); 80 | 81 | lock (this.root) 82 | { 83 | if (this.timer != null) 84 | { 85 | this.timer.Dispose(); 86 | this.timer = null; 87 | 88 | this.callback(this); 89 | } 90 | } 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/CookieHttpHandler.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net; 3 | using System.Net.Http; 4 | using System.Threading; 5 | using System.Threading.Tasks; 6 | 7 | namespace HttpMessageHandlerFactory 8 | { 9 | /// 10 | /// cookie处理者 11 | /// 12 | sealed class CookieHttpHandler : DelegatingHandler 13 | { 14 | private const string COOKIE_HEADER = "Cookie"; 15 | private const string SET_COOKIE_HEADER = "Set-Cookie"; 16 | private readonly CookieContainer cookieContainer; 17 | 18 | public CookieHttpHandler(HttpMessageHandler innerHandler, CookieContainer cookieContainer) 19 | { 20 | this.InnerHandler = innerHandler; 21 | this.cookieContainer = cookieContainer; 22 | } 23 | 24 | protected override HttpResponseMessage Send(HttpRequestMessage request, CancellationToken cancellationToken) 25 | { 26 | UseCookie(request, this.cookieContainer); 27 | var response = base.Send(request, cancellationToken); 28 | SetCookie(request.RequestUri, response, this.cookieContainer); 29 | return response; 30 | } 31 | 32 | protected async override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 33 | { 34 | UseCookie(request, this.cookieContainer); 35 | var response = await base.SendAsync(request, cancellationToken); 36 | SetCookie(request.RequestUri, response, this.cookieContainer); 37 | return response; 38 | } 39 | 40 | /// 41 | /// 使用Cookie到请求 42 | /// 43 | /// 44 | /// 45 | private static void UseCookie( 46 | HttpRequestMessage reqeust, 47 | CookieContainer cookieContainer) 48 | { 49 | var requestUri = reqeust.RequestUri; 50 | if (requestUri == null || requestUri.IsAbsoluteUri == false) 51 | { 52 | return; 53 | } 54 | 55 | var cookieHeader = cookieContainer.GetCookieHeader(requestUri); 56 | reqeust.Headers.TryAddWithoutValidation(COOKIE_HEADER, cookieHeader); 57 | } 58 | 59 | 60 | /// 61 | /// 设置Cookie到CookieContainer 62 | /// 63 | /// 64 | /// 65 | /// 66 | private static void SetCookie( 67 | Uri? requestUri, 68 | HttpResponseMessage response, 69 | CookieContainer cookieContainer) 70 | { 71 | if (requestUri == null || 72 | response.Headers.TryGetValues(SET_COOKIE_HEADER, out var cookies) == false) 73 | { 74 | return; 75 | } 76 | 77 | foreach (var cookieHeader in cookies) 78 | { 79 | try 80 | { 81 | cookieContainer.SetCookies(requestUri, cookieHeader); 82 | } 83 | catch (CookieException) 84 | { 85 | } 86 | } 87 | } 88 | 89 | } 90 | } 91 | 92 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/Implementations/HttpMessageHandlerBuilder.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Options; 2 | using System; 3 | using System.Diagnostics.CodeAnalysis; 4 | using System.Net; 5 | using System.Net.Http; 6 | 7 | namespace HttpMessageHandlerFactory.Implementations 8 | { 9 | /// 10 | /// HttpMessageHandler创建器 11 | /// 12 | sealed class HttpMessageHandlerBuilder 13 | { 14 | private readonly IServiceProvider serviceProvider; 15 | private readonly IOptionsMonitor options; 16 | 17 | /// 18 | /// 获取或设置别名和代理 19 | /// 20 | [NotNull] 21 | public NameProxy? NameProxy { get; set; } 22 | 23 | /// 24 | /// 获取生命周期 25 | /// 26 | /// 27 | public TimeSpan GetLifetime() 28 | { 29 | return this.options.Get(this.NameProxy.Name).Lifetime; 30 | } 31 | 32 | /// 33 | /// HttpMessageHandler创建器 34 | /// 35 | /// 36 | /// 37 | public HttpMessageHandlerBuilder( 38 | IServiceProvider serviceProvider, 39 | IOptionsMonitor options) 40 | { 41 | this.serviceProvider = serviceProvider; 42 | this.options = options; 43 | } 44 | 45 | /// 46 | /// 创建链式调用的 47 | /// 48 | /// 49 | public HttpMessageHandler Build() 50 | { 51 | var next = this.BuildPrimary(); 52 | var additionalHandlers = this.options.Get(this.NameProxy.Name).AdditionalHandlers; 53 | 54 | for (var i = additionalHandlers.Count - 1; i >= 0; i--) 55 | { 56 | var handler = additionalHandlers[i](serviceProvider); 57 | handler.InnerHandler = next; 58 | next = handler; 59 | } 60 | 61 | return next; 62 | } 63 | 64 | /// 65 | /// 创建基础消息处理者 66 | /// 67 | /// 68 | private HttpMessageHandler BuildPrimary() 69 | { 70 | var primaryHandler = new SocketsHttpHandler 71 | { 72 | UseCookies = false 73 | }; 74 | 75 | var proxyUri = this.NameProxy.ProxyUri; 76 | if (proxyUri == null) 77 | { 78 | primaryHandler.UseProxy = false; 79 | } 80 | else 81 | { 82 | primaryHandler.UseProxy = true; 83 | primaryHandler.Proxy = new WebProxy(proxyUri) { Credentials = GetCredential(proxyUri) }; 84 | } 85 | 86 | var configures = this.options.Get(this.NameProxy.Name).PrimaryHandlerConfigures; 87 | foreach (var configure in configures) 88 | { 89 | configure(serviceProvider, primaryHandler); 90 | } 91 | 92 | return primaryHandler; 93 | } 94 | 95 | /// 96 | /// 获取身份 97 | /// 98 | /// 99 | /// 100 | private static NetworkCredential? GetCredential(Uri uri) 101 | { 102 | var userInfo = uri.UserInfo; 103 | if (string.IsNullOrEmpty(userInfo)) 104 | { 105 | return null; 106 | } 107 | 108 | var index = userInfo.IndexOf(':'); 109 | if (index < 0) 110 | { 111 | return new NetworkCredential(userInfo, default(string)); 112 | } 113 | 114 | var username = userInfo[..index]; 115 | var password = userInfo[(index + 1)..]; 116 | return new NetworkCredential(username, password); 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # HttpMessageHandlerFactory 2 | 具有生命周期管理和动态Web代理的HttpMessageHandler创建工厂 3 | 4 | | nuget包 | 状态 | 说明 | 5 | | ------------------------------------ | --------------------------------------------------------------------------------- | -------------- | 6 | | HttpMessageHandlerFactory | ![NuGet logo](https://buildstats.info/nuget/HttpMessageHandlerFactory) | MIT开源 | 7 | | HttpMessageHandlerFactory.Polly | ![NuGet logo](https://buildstats.info/nuget/HttpMessageHandlerFactory.Polly) | MIT开源 | 8 | | HttpMessageHandlerFactory.Connection | ![NuGet logo](https://buildstats.info/nuget/HttpMessageHandlerFactory.Connection) | 闭源,需要授权 | 9 | 10 | ## 1 功能介绍 11 | ### 1.1 CreateHandler 12 | ```c# 13 | /// 14 | /// 创建用于请求的HttpMessageHandler 15 | /// 16 | /// 别名 17 | /// 支持携带UserInfo的代理地址 18 | /// 19 | HttpMessageHandler CreateHandler(string name, Uri? proxyUri); 20 | ``` 21 | ### 1.2 CreateClient 22 | 将CreateHandler()产生的`HttpMessageHandler`包装为`HttpClient`,适用于客户端直接请求。 23 | 24 | ### 1.3 CreateInvoker 25 | 将CreateHandler()产生的`HttpMessageHandler`包装为`HttpMessageInvoker`,适用于反向代理中间件(比如YARP)的请求转发。 26 | 27 | ## 2 使用示例 28 | ```c# 29 | static async Task Main(string[] args) 30 | { 31 | var services = new ServiceCollection(); 32 | services.AddLogging(x => x.AddConsole()); 33 | services.AddHttpMessageHandlerFactory("App") 34 | .AddHttpMessageHandler() 35 | .SetHandlerLifetime(TimeSpan.FromMinutes(1d)); 36 | 37 | var serviceProvider = services.BuildServiceProvider(); 38 | var factory = serviceProvider.GetRequiredService(); 39 | 40 | var proxyUri = default(Uri); 41 | var httpClient = factory.CreateClient("App", proxyUri); 42 | var html = await httpClient.GetStringAsync("https://github.com/xljiulang/HttpMessageHandlerFactory/blob/master/README.md"); 43 | Console.WriteLine(html); 44 | } 45 | ``` 46 | 47 | ## 3 扩展项目 48 | ### 3.1 HttpMessageHandlerFactory.Polly 49 | 为HttpMessageHandlerFactory提供Polly策略扩展,使得`IHttpMessageHandlerBuilder`拥有与`IHttpClientFactory`完全一致的Polly能力。 50 | 51 | #### 3.1.1 AddPolicyHandler能力 52 | ```c# 53 | var retryPolicy = Policy.Handle() 54 | .OrResult(response => 55 | { 56 | return response.IsSuccessStatusCode == false; 57 | }).WaitAndRetryAsync(3, t => TimeSpan.FromSeconds(3d)); 58 | 59 | services 60 | .AddHttpMessageHandlerFactory("App") 61 | .AddPolicyHandler(retryPolicy); 62 | ``` 63 | 64 | #### 3.1.2 AddPolicyHandlerFromRegistry能力 65 | ```c# 66 | var retryPolicy = Policy.Handle() 67 | .OrResult(response => 68 | { 69 | return response.IsSuccessStatusCode == false; 70 | }).WaitAndRetryAsync(3, t => TimeSpan.FromSeconds(3d)); 71 | 72 | var registry = services.AddPolicyRegistry(); 73 | registry.Add("registry1", retryPolicy); 74 | 75 | services 76 | .AddHttpMessageHandlerFactory("App") 77 | .AddPolicyHandlerFromRegistry("registry1"); 78 | ``` 79 | 80 | #### 3.1.3 AddTransientHttpErrorPolicy能力 81 | 当以下任意条件成立时,触发TransientHttpErrorPolicy 82 | * HttpRequestException的网络故障 83 | * 服务端响应5XX的状态码 84 | * 408的状态码(request timeout) 85 | 86 | ```c# 87 | services 88 | .AddHttpMessageHandlerFactory("App") 89 | .AddTransientHttpErrorPolicy(builder => builder.WaitAndRetryAsync(new[] { 90 | TimeSpan.FromSeconds(1d), 91 | TimeSpan.FromSeconds(5d), 92 | TimeSpan.FromSeconds(10d) 93 | })); 94 | ``` 95 | 96 | 97 | ### 3.2 HttpMessageHandlerFactory.Connection 98 | 为HttpMessageHandlerFactory提供自定义连接的功能。 99 | 注意此扩展项目不是免费项目,有如下限制: 100 | * 不开放和提供源代码 101 | * nuget包的程序集在应用程序运行2分钟后适用期结束 102 | * 适用期结束后所有的http请求响应为423 Locked 103 | * 需要license文件授权方可完全使用 104 | 105 | #### 3.2.1 自定义域名解析 106 | * 当无代理连接时,连接到自定义解析得到的IP 107 | * 当使用http代理时,让代理服务器连接到自定义解析得到的IP 108 | * 当使用socks代理时,让代理服务器连接到自定义解析得到的IP 109 | 110 | ```c# 111 | services 112 | .AddHttpMessageHandlerFactory("App") 113 | .AddHostResolver(); 114 | ``` 115 | 116 | ```c# 117 | sealed class CustomHostResolver : HostResolver 118 | { 119 | public override ValueTask ResolveAsync(DnsEndPoint endpoint, CancellationToken cancellationToken) 120 | { 121 | if (endpoint.Host == "www.baidu.com") 122 | { 123 | return ValueTask.FromResult(new HostPort("14.119.104.189", endpoint.Port)); 124 | } 125 | return ValueTask.FromResult(new HostPort(endpoint.Host, endpoint.Port)); 126 | } 127 | } 128 | ``` 129 | #### 3.2.2 自定义ssl的sni 130 | ```c# 131 | services 132 | .AddHttpMessageHandlerFactory("App") 133 | .AddSslSniProvider(); 134 | ``` 135 | 136 | ```c# 137 | sealed class CustomSslSniProvider : SslSniProvider 138 | { 139 | public override ValueTask GetSslSniAsync(string host, CancellationToken cancellationToken) 140 | { 141 | return ValueTask.FromResult(string.Empty); 142 | } 143 | 144 | public override bool RemoteCertificateValidationCallback(string host, X509Certificate? cert, X509Chain? chain, SslPolicyErrors errors) 145 | { 146 | return true; 147 | } 148 | } 149 | ``` 150 | 151 | ## 4 开源有你 152 | ![赞助](donate2laojiu.png) -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/DependencyInjection/HttpMessageHandlerBuilderExtensions.cs: -------------------------------------------------------------------------------- 1 | using HttpMessageHandlerFactory; 2 | using Microsoft.Extensions.DependencyInjection.Extensions; 3 | using Microsoft.Extensions.Options; 4 | using System; 5 | using System.Net; 6 | using System.Net.Http; 7 | 8 | namespace Microsoft.Extensions.DependencyInjection 9 | { 10 | /// 11 | /// IHttpMessageHandlerBuilder扩展 12 | /// 13 | public static class HttpMessageHandlerBuilderExtensions 14 | { 15 | /// 16 | /// 配置为反向代理模式以支持YARP等框架 17 | /// .UseCookies = false 18 | /// .AllowAutoRedirect = false 19 | /// .ActivityHeadersPropagator = null 20 | /// .AutomaticDecompression = DecompressionMethods.None 21 | /// 22 | /// 23 | /// 24 | public static IHttpMessageHandlerBuilder ConfigureAsReverseProxy(this IHttpMessageHandlerBuilder builder) 25 | { 26 | return builder.ConfigurePrimaryHttpMessageHandler(handler => 27 | { 28 | handler.UseCookies = false; 29 | handler.AllowAutoRedirect = false; 30 | handler.ActivityHeadersPropagator = null; 31 | handler.AutomaticDecompression = DecompressionMethods.None; 32 | }); 33 | } 34 | 35 | /// 36 | /// 设置生命周期 37 | /// 38 | /// 39 | /// 40 | /// 41 | /// 42 | public static IHttpMessageHandlerBuilder SetHandlerLifetime(this IHttpMessageHandlerBuilder builder, TimeSpan handlerLifetime) 43 | { 44 | if (handlerLifetime <= TimeSpan.Zero) 45 | { 46 | throw new ArgumentOutOfRangeException(nameof(handlerLifetime)); 47 | } 48 | 49 | builder.AddOptions().Configure(options => options.Lifetime = handlerLifetime); 50 | return builder; 51 | } 52 | 53 | 54 | /// 55 | /// 添加管道HttpMessageHandler 56 | /// 57 | /// 58 | /// 59 | /// 60 | public static IHttpMessageHandlerBuilder AddHttpMessageHandler(this IHttpMessageHandlerBuilder builder) 61 | where THandler : DelegatingHandler 62 | { 63 | builder.Services.TryAddTransient(); 64 | return builder.AddHttpMessageHandler(serviceProvider => serviceProvider.GetRequiredService()); 65 | } 66 | 67 | /// 68 | /// 添加管道HttpMessageHandler 69 | /// 70 | /// 71 | /// 72 | /// 73 | public static IHttpMessageHandlerBuilder AddHttpMessageHandler(this IHttpMessageHandlerBuilder builder, Func configureHandler) 74 | { 75 | return builder.AddHttpMessageHandler(serviceProvider => configureHandler()); 76 | } 77 | 78 | /// 79 | /// 添加管道HttpMessageHandler 80 | /// 81 | /// 82 | /// 83 | /// 84 | public static IHttpMessageHandlerBuilder AddHttpMessageHandler(this IHttpMessageHandlerBuilder builder, Func configureHandler) 85 | { 86 | builder.AddOptions().Configure(options => options.AdditionalHandlers.Add(configureHandler)); 87 | return builder; 88 | } 89 | 90 | /// 91 | /// 配置主要的HttpMessageHandler 92 | /// 93 | /// 94 | /// 95 | /// 96 | public static IHttpMessageHandlerBuilder ConfigurePrimaryHttpMessageHandler(this IHttpMessageHandlerBuilder builder, Action configureHandler) 97 | { 98 | return builder.ConfigurePrimaryHttpMessageHandler((serviceProvider, httpHandler) => configureHandler(httpHandler)); 99 | } 100 | 101 | /// 102 | /// 配置主要的HttpMessageHandler 103 | /// 104 | /// 105 | /// 106 | /// 107 | public static IHttpMessageHandlerBuilder ConfigurePrimaryHttpMessageHandler(this IHttpMessageHandlerBuilder builder, Action configureHandler) 108 | { 109 | builder.AddOptions().Configure(options => options.PrimaryHandlerConfigures.Add(configureHandler)); 110 | return builder; 111 | } 112 | 113 | 114 | /// 115 | /// 添加选项 116 | /// 117 | /// 118 | /// 119 | private static OptionsBuilder AddOptions(this IHttpMessageHandlerBuilder builder) 120 | { 121 | return builder.Services.AddOptions(builder.Name); 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/Implementations/DefaultHttpMessageHandlerFactory.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using System; 3 | using System.Collections.Concurrent; 4 | using System.Diagnostics; 5 | using System.Net.Http; 6 | using System.Threading; 7 | 8 | namespace HttpMessageHandlerFactory.Implementations 9 | { 10 | /// 11 | /// 默认的Http消息处理者工厂 12 | /// 13 | sealed class DefaultHttpMessageHandlerFactory : IHttpMessageHandlerFactory 14 | { 15 | private readonly NameRegistration nameRegistration; 16 | private readonly IServiceScopeFactory serviceScopeFactory; 17 | private readonly ExpiredHandlerEntryCleaner expiredHandlerEntryCleaner; 18 | 19 | /// 20 | /// 过期回调 21 | /// 22 | private readonly TimerCallback expiryCallback; 23 | 24 | /// 25 | /// LazyOf(ActiveHandlerEntry)缓存 26 | /// 27 | private readonly ConcurrentDictionary> activeHandlerEntries = new(); 28 | 29 | /// 30 | /// Http消息处理者工厂 31 | /// 32 | /// 33 | /// 34 | /// 35 | public DefaultHttpMessageHandlerFactory( 36 | NameRegistration nameRegistration, 37 | IServiceScopeFactory serviceScopeFactory, 38 | ExpiredHandlerEntryCleaner expiredHandlerEntryCleaner) 39 | { 40 | this.nameRegistration = nameRegistration; 41 | this.serviceScopeFactory = serviceScopeFactory; 42 | this.expiredHandlerEntryCleaner = expiredHandlerEntryCleaner; 43 | 44 | this.expiryCallback = this.ExpiryTimer_Tick; 45 | } 46 | 47 | /// 48 | /// 创建用于请求的HttpMessageHandler 49 | /// 50 | /// 别名 51 | /// 支持携带UserInfo的代理地址 52 | /// 53 | public HttpMessageHandler CreateHandler(string name, Uri? proxyUri) 54 | { 55 | if (this.nameRegistration.Contains(name) == false) 56 | { 57 | throw new InvalidOperationException($"尚未登记别名为 {name} 的HttpMessageHandler"); 58 | } 59 | 60 | var nameProxy = new NameProxy(name, proxyUri); 61 | var ativeEntry = this.activeHandlerEntries.GetOrAdd(nameProxy, this.CreateActiveHandlerEntryLazy).Value; 62 | ativeEntry.StartExpiryTimer(this.expiryCallback); 63 | return ativeEntry.LifetimeHttpHandler; 64 | } 65 | 66 | /// 67 | /// 创建LazyOf(ActiveHandlerEntry) 68 | /// 69 | /// 70 | /// 71 | private Lazy CreateActiveHandlerEntryLazy(NameProxy nameProxy) 72 | { 73 | return new Lazy(() => this.CreateActiveHandlerEntry(nameProxy), LazyThreadSafetyMode.ExecutionAndPublication); 74 | } 75 | 76 | /// 77 | /// 创建ActiveHandlerEntry 78 | /// 79 | /// 80 | /// 81 | private ActiveHandlerEntry CreateActiveHandlerEntry(NameProxy nameProxy) 82 | { 83 | var serviceScope = this.serviceScopeFactory.CreateScope(); 84 | var serviceProvider = serviceScope.ServiceProvider; 85 | 86 | var builder = serviceProvider.GetRequiredService(); 87 | builder.NameProxy = nameProxy; 88 | var httpHandler = builder.Build(); 89 | var lifetime = builder.GetLifetime(); 90 | 91 | var lifeTimeHandler = new LifetimeHttpHandler(httpHandler); 92 | return new ActiveHandlerEntry(lifetime, nameProxy, serviceScope, lifeTimeHandler); 93 | } 94 | 95 | 96 | /// 97 | /// 过期timer回调 98 | /// 99 | /// 100 | private void ExpiryTimer_Tick(object? state) 101 | { 102 | var ativeEntry = (ActiveHandlerEntry)state!; 103 | 104 | // The timer callback should be the only one removing from the active collection. If we can't find 105 | // our entry in the collection, then this is a bug. 106 | var removed = this.activeHandlerEntries.TryRemove(ativeEntry.NameProxy, out Lazy? found); 107 | Debug.Assert(removed, "Entry not found. We should always be able to remove the entry"); 108 | Debug.Assert(object.ReferenceEquals(ativeEntry, found!.Value), "Different entry found. The entry should not have been replaced"); 109 | 110 | // At this point the handler is no longer 'active' and will not be handed out to any new clients. 111 | // However we haven't dropped our strong reference to the handler, so we can't yet determine if 112 | // there are still any other outstanding references (we know there is at least one). 113 | 114 | // We use a different state object to track expired handlers. This allows any other thread that acquired 115 | // the 'active' entry to use it without safety problems. 116 | var expiredEntry = new ExpiredHandlerEntry(ativeEntry); 117 | this.expiredHandlerEntryCleaner.Add(expiredEntry); 118 | } 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /HttpMessageHandlerFactory/Implementations/ExpiredHandlerEntryCleaner.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using Microsoft.Extensions.Logging.Abstractions; 3 | using System; 4 | using System.Collections.Concurrent; 5 | using System.Diagnostics; 6 | using System.Threading; 7 | 8 | namespace HttpMessageHandlerFactory.Implementations 9 | { 10 | /// 11 | /// 已过期的条目清除器 12 | /// https://github.com/dotnet/runtime/blob/v7.0.0/src/libraries/Microsoft.Extensions.Http/src/DefaultHttpClientFactory.cs 13 | /// 14 | sealed partial class ExpiredHandlerEntryCleaner 15 | { 16 | private static readonly TimeSpan cleanupInterval = TimeSpan.FromSeconds(10d); 17 | private static readonly TimerCallback cleanupCallback = s => ((ExpiredHandlerEntryCleaner)s!).CleanupTimer_Tick(); 18 | 19 | private Timer? cleanupTimer; 20 | private readonly object cleanupTimerLock = new(); 21 | private readonly object cleanupActiveLock = new(); 22 | private readonly ConcurrentQueue expiredHandlerEntries = new(); 23 | private readonly ILogger logger; 24 | 25 | /// 26 | /// 已过期的条目清除器 27 | /// 28 | public ExpiredHandlerEntryCleaner() 29 | : this(NullLogger.Instance) 30 | { 31 | } 32 | 33 | /// 34 | /// 已过期的条目清除器 35 | /// 36 | /// 37 | public ExpiredHandlerEntryCleaner(ILogger logger) 38 | { 39 | this.logger = logger; 40 | } 41 | 42 | /// 43 | /// 添加过期条目 44 | /// 45 | /// 46 | public void Add(ExpiredHandlerEntry expiredEntry) 47 | { 48 | Log.HandlerExpired(this.logger, expiredEntry.NameProxy.Name); 49 | 50 | this.expiredHandlerEntries.Enqueue(expiredEntry); 51 | this.StartCleanupTimer(); 52 | } 53 | 54 | /// 55 | /// 启动清洁 56 | /// 57 | private void StartCleanupTimer() 58 | { 59 | lock (this.cleanupTimerLock) 60 | { 61 | this.cleanupTimer ??= NonCapturingTimer.Create(cleanupCallback, this, cleanupInterval, Timeout.InfiniteTimeSpan); 62 | } 63 | } 64 | 65 | /// 66 | /// 停止清洁 67 | /// 68 | private void StopCleanupTimer() 69 | { 70 | lock (this.cleanupTimerLock) 71 | { 72 | this.cleanupTimer!.Dispose(); 73 | this.cleanupTimer = null; 74 | } 75 | } 76 | 77 | 78 | private void CleanupTimer_Tick() 79 | { 80 | // Stop any pending timers, we'll restart the timer if there's anything left to process after cleanup. 81 | // 82 | // With the scheme we're using it's possible we could end up with some redundant cleanup operations. 83 | // This is expected and fine. 84 | // 85 | // An alternative would be to take a lock during the whole cleanup process. This isn't ideal because it 86 | // would result in threads executing ExpiryTimer_Tick as they would need to block on cleanup to figure out 87 | // whether we need to start the timer. 88 | this.StopCleanupTimer(); 89 | 90 | if (!Monitor.TryEnter(this.cleanupActiveLock)) 91 | { 92 | // We don't want to run a concurrent cleanup cycle. This can happen if the cleanup cycle takes 93 | // a long time for some reason. Since we're running user code inside Dispose, it's definitely 94 | // possible. 95 | // 96 | // If we end up in that position, just make sure the timer gets started again. It should be cheap 97 | // to run a 'no-op' cleanup. 98 | this.StartCleanupTimer(); 99 | return; 100 | } 101 | 102 | try 103 | { 104 | 105 | var initialCount = expiredHandlerEntries.Count; 106 | Log.CleanupCycleStart(this.logger, initialCount); 107 | 108 | var disposedCount = 0; 109 | for (var i = 0; i < initialCount; i++) 110 | { 111 | // Since we're the only one removing from _expired, TryDequeue must always succeed. 112 | this.expiredHandlerEntries.TryDequeue(out ExpiredHandlerEntry? entry); 113 | Debug.Assert(entry != null, "Entry was null, we should always get an entry back from TryDequeue"); 114 | 115 | if (entry.CanDispose) 116 | { 117 | try 118 | { 119 | entry.InnerHandler.Dispose(); 120 | entry.ServiceScope.Dispose(); 121 | disposedCount++; 122 | } 123 | catch (Exception ex) 124 | { 125 | Log.CleanupItemFailed(this.logger, entry.NameProxy.Name, ex); 126 | } 127 | } 128 | else 129 | { 130 | // If the entry is still live, put it back in the queue so we can process it 131 | // during the next cleanup cycle. 132 | this.expiredHandlerEntries.Enqueue(entry); 133 | } 134 | } 135 | Log.CleanupCycleEnd(this.logger, disposedCount, this.expiredHandlerEntries.Count); 136 | } 137 | finally 138 | { 139 | Monitor.Exit(this.cleanupActiveLock); 140 | } 141 | 142 | // We didn't totally empty the cleanup queue, try again later. 143 | if (!expiredHandlerEntries.IsEmpty) 144 | { 145 | this.StartCleanupTimer(); 146 | } 147 | } 148 | 149 | static partial class Log 150 | { 151 | [LoggerMessage(0, LogLevel.Debug, "Starting HttpMessageHandler cleanup cycle with {initialCount} items")] 152 | public static partial void CleanupCycleStart(ILogger logger, int initialCount); 153 | 154 | [LoggerMessage(1, LogLevel.Debug, "Ending HttpMessageHandler cleanup, processed {disposedCount} items, remaining {remaining} items")] 155 | public static partial void CleanupCycleEnd(ILogger logger, int disposedCount, int remaining); 156 | 157 | [LoggerMessage(2, LogLevel.Debug, "HttpMessageHandler.Dispose() threw an unhandled exception for '{name}'")] 158 | public static partial void CleanupItemFailed(ILogger logger, string name, Exception exception); 159 | 160 | [LoggerMessage(3, LogLevel.Debug, "HttpMessageHandler expired for '{name}'")] 161 | public static partial void HandlerExpired(ILogger logger, string name); 162 | } 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd 364 | /SniProxy/cacert 365 | --------------------------------------------------------------------------------