|
| 1 | +// ReSharper disable CheckNamespace |
| 2 | + |
| 3 | +using System; |
| 4 | +using System.Net.Http; |
| 5 | +using System.Net.Security; |
| 6 | +using System.Security.Cryptography.X509Certificates; |
| 7 | +using Microsoft.Extensions.DependencyInjection; |
| 8 | + |
| 9 | +namespace Microsoft.Extensions.Http |
| 10 | +{ |
| 11 | + /// <summary> |
| 12 | + /// A set of extension methods for <see cref="IHttpClientBuilder" />. |
| 13 | + /// </summary> |
| 14 | + public static class HttpClientBuilderExtensions |
| 15 | + { |
| 16 | +#if NET5_0 || NETSTANDARD |
| 17 | + /// <summary> |
| 18 | + /// Configures the primary HTTP message handler to validate SSL certificates using the specified <paramref name="callback"/>. |
| 19 | + /// </summary> |
| 20 | + /// <param name="builder">The instance of <see cref="IHttpClientBuilder" /> to extend.</param> |
| 21 | + /// <param name="callback">The callback to be used to validate SSL certificates.</param> |
| 22 | + /// <returns>The same instance of <see cref="IHttpClientBuilder" /> passed in <paramref name="builder"/>.</returns> |
| 23 | + /// <exception cref="ArgumentNullException"><paramref name="builder"/> cannot be null.</exception> |
| 24 | + /// <exception cref="ArgumentNullException"><paramref name="callback"/> cannot be null.</exception> |
| 25 | + public static IHttpClientBuilder ConfigureSslCertificateValidation(this IHttpClientBuilder builder, Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> callback) |
| 26 | + { |
| 27 | + _ = builder ?? throw new ArgumentNullException(nameof(builder)); |
| 28 | + |
| 29 | + _ = callback ?? throw new ArgumentNullException(nameof(callback)); |
| 30 | + |
| 31 | + _ = builder.ConfigurePrimaryHttpMessageHandler(() => |
| 32 | + { |
| 33 | + var handler = new HttpClientHandler |
| 34 | + { |
| 35 | + ServerCertificateCustomValidationCallback = callback, |
| 36 | + }; |
| 37 | + |
| 38 | + return handler; |
| 39 | + }); |
| 40 | + |
| 41 | + return builder; |
| 42 | + } |
| 43 | + |
| 44 | + /// <summary> |
| 45 | + /// Configures the primary HTTP message handler to always accept incoming SSL certificates. |
| 46 | + /// </summary> |
| 47 | + /// <param name="builder">The instance of <see cref="IHttpClientBuilder" /> to extend.</param> |
| 48 | + /// <returns>The same instance of <see cref="IHttpClientBuilder" /> passed in <paramref name="builder"/>.</returns> |
| 49 | + /// <exception cref="ArgumentNullException"><paramref name="builder"/> cannot be null.</exception> |
| 50 | + public static IHttpClientBuilder DisableSslCertificateValidation(this IHttpClientBuilder builder) => ConfigureSslCertificateValidation(builder, (_, _, _, _) => true); |
| 51 | +#endif |
| 52 | + } |
| 53 | +} |
0 commit comments