78 lines
2.3 KiB
C#
78 lines
2.3 KiB
C#
using Grpc.Net.Client;
|
|
using EonaCat.Connections.Models;
|
|
using System.Net.Security;
|
|
using System.Security.Authentication;
|
|
|
|
namespace EonaCat.Connections.gRPC
|
|
{
|
|
|
|
public static class GrpcChannelFactory
|
|
{
|
|
|
|
public static GrpcChannel Create(Configuration config)
|
|
{
|
|
if (config == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(config));
|
|
}
|
|
|
|
var scheme = config.UseSsl ? "https" : "http";
|
|
var address = $"{scheme}://{config.Host}:{config.Port}";
|
|
return Create(address, config);
|
|
}
|
|
|
|
public static GrpcChannel Create(string address, Configuration config)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(address))
|
|
{
|
|
throw new ArgumentNullException(nameof(address));
|
|
}
|
|
|
|
if (config == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(config));
|
|
}
|
|
|
|
return GrpcChannel.ForAddress(address, BuildChannelOptions(config));
|
|
}
|
|
|
|
public static GrpcChannelOptions BuildChannelOptions(Configuration config)
|
|
{
|
|
if (config == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(config));
|
|
}
|
|
|
|
var options = new GrpcChannelOptions();
|
|
|
|
if (config.UseSsl)
|
|
{
|
|
options.HttpHandler = new SocketsHttpHandler
|
|
{
|
|
SslOptions = new SslClientAuthenticationOptions
|
|
{
|
|
EnabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls13,
|
|
RemoteCertificateValidationCallback = (sender, certificate, chain, errors) =>
|
|
{
|
|
if (config.IsSelfSignedEnabled)
|
|
{
|
|
return true;
|
|
}
|
|
return errors == SslPolicyErrors.None;
|
|
}
|
|
}
|
|
};
|
|
}
|
|
else
|
|
{
|
|
options.HttpHandler = new SocketsHttpHandler
|
|
{
|
|
EnableMultipleHttp2Connections = true
|
|
};
|
|
}
|
|
|
|
return options;
|
|
}
|
|
}
|
|
}
|