如何让 gRPC 客户端与不同机器上的 gRPC 服务器通信?两者都在 Asp Net Core 3.0 中。可能的 SSL 问题

How to make gRPC client comunicate with a gRPC server in a different machine? Both in Aspnet Core 3.0. Possible SSL problem

因此,通过标题您就知道我要构建的是什么。

我已经有一个 gRPC 服务器和 3 个客户端在同一台机器上进行通信。服务器可在 http://localhot:5001 上访问。一切 运行 都很顺利,但如果我 运行 客户端在另一台机器上,它们将无法访问服务器。所以我安装了 IIS 并将服务器放在那里,以便通过域 beta.server.com 向外部提供服务。我更改了客户端计算机上的主机文件以转到服务器在 IIS 上 运行ning 的计算机 ip(192.168.5.49)。

当我尝试通过 http 访问浏览器时,我收到一条消息说我只能连接 gRPC 客户端。通过 https 表示 NET::ERR_CERT_COMMON_NAME_INVALID。可能就是这个问题吧。。。(写完后才发现)。

通过尝试将 gRPC 客户端连接到 http(http://beta.server.com),我收到一条错误消息,指出 http/1.1 不受支持,这是事实,此服务仅适用于 http2。

当尝试使用 https(https://beta.server.com) 连接到服务器 ip 时,我收到无法建立 ssl 连接的错误。如下:

PS C:\Users\Farm\Desktop\GrpcSierConsole\Viewer> dotnet run
Entered task
Unhandled exception. System.AggregateException: One or more errors occurred. (Status(StatusCode=Internal, Detail="Error starting gRPC call: The SSL connection could not be established, see inner exception."))
 ---> Grpc.Core.RpcException: Status(StatusCode=Internal, Detail="Error starting gRPC call: The SSL connection could not be established, see inner exception.")
   at Grpc.Net.Client.Internal.HttpContentClientStreamReader`2.MoveNextCore(CancellationToken cancellationToken)
   at Grpc.Core.AsyncStreamReaderExtensions.ReadAllAsync[T](IAsyncStreamReader`1 streamReader, CancellationToken cancellationToken)+MoveNext()
   at Grpc.Core.AsyncStreamReaderExtensions.ReadAllAsync[T](IAsyncStreamReader`1 streamReader, CancellationToken cancellationToken)+System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult()
   at Viewer.Program.<>c.<<Main>b__0_0>d.MoveNext() in C:\Users\Farm\Desktop\GrpcSierConsole\viewer\Program.cs:line 24
--- End of stack trace from previous location where exception was thrown ---
   at Viewer.Program.<>c.<<Main>b__0_0>d.MoveNext() in C:\Users\Farm\Desktop\GrpcSierConsole\viewer\Program.cs:line 24
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at Viewer.Program.Main() in C:\Users\Farm\Desktop\GrpcSierConsole\viewer\Program.cs:line 29

错误在服务器 program.cs 的第 29 行。我的代码如下: 第 29 行是 webBuilder.UseStartup():

//Additional configuration is required to successfully run gRPC on macOS.
        // For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });

我尝试在客户端计算机和服务器计算机 运行ning IIS 中使用 Visual Studio 本地主机证书和 IIS 中的自签名证书。

此外,我在客户端中使用了这一行来信任所有证书:

ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

我从中得到的:How to ignore the certificate check when ssl

我不知道还能做什么。有人可以帮忙吗?

#####################更新####################

我已将此代码添加到客户端

var httpClientHandler = new HttpClientHandler();
// Return `true` to allow certificates that are untrusted/invalid
httpClientHandler.ServerCertificateCustomValidationCallback = 
    HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
var httpClient = new HttpClient(httpClientHandler);

var channel = GrpcChannel.ForAddress("https://localhost:5001",
    new GrpcChannelOptions { HttpClient = httpClient });
 var client = new QueueManagement.QueueManagementClient(channel);
...

现在我没有 SSL 错误,但是这个:

PS C:\Users\Farm\Desktop\GrpcSierConsole\Viewer> dotnet run
Entered task
Unhandled exception. System.AggregateException: One or more errors occurred. (Status(StatusCode=Internal, Detail="Error starting gRPC call: An error occurred while sending the request."))
 ---> Grpc.Core.RpcException: Status(StatusCode=Internal, Detail="Error starting gRPC call: An error occurred while sending the request.")
   at Grpc.Net.Client.Internal.HttpContentClientStreamReader`2.MoveNextCore(CancellationToken cancellationToken)
   at Grpc.Core.AsyncStreamReaderExtensions.ReadAllAsync[T](IAsyncStreamReader`1 streamReader, CancellationToken cancellationToken)+MoveNext()
   at Grpc.Core.AsyncStreamReaderExtensions.ReadAllAsync[T](IAsyncStreamReader`1 streamReader, CancellationToken cancellationToken)+System.Threading.Tasks.Sources.IValueTaskSource<System.Boolean>.GetResult()
   at Viewer.Program.<>c.<<Main>b__0_0>d.MoveNext() in C:\Users\Farm\Desktop\GrpcSierConsole\Viewer\Program.cs:line 32
--- End of stack trace from previous location where exception was thrown ---
   at Viewer.Program.<>c.<<Main>b__0_0>d.MoveNext() in C:\Users\Farm\Desktop\GrpcSierConsole\Viewer\Program.cs:line 32
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at Viewer.Program.Main() in C:\Users\Farm\Desktop\GrpcSierConsole\Viewer\Program.cs:line 37

在第 37 行我有 task.wait() 因为这个 运行s 在任务中。

var channel = GrpcChannel.ForAddress("https://beta.server.com",
    new GrpcChannelOptions { HttpClient = httpClient });
                var client = new QueueManagement.QueueManagementClient(channel);

                var request = client.QueueNumberChanged(new SendQueueId { QueueId = "2" });
                await foreach (var response in request.ResponseStream.ReadAllAsync())
                {
                    Console.WriteLine($"Senha {response.Number} -> fila 2");
                }
            });
            t.Wait();

经过大量研究并在 Microsoft 官方 GitHub .Net Core kestrel 文档存储库中交换了许多消息后,我找到了它。

可以在 appsettings.json

上使用此设置完成
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "Kestrel": {
    "EndpointDefaults": {
      "Protocols": "Http2"
    },
    "EndPoints": {
      "Https": {
        "Url": "https://*:5002",
        "Certificate": {
          "Path": "c:\test.pfx",
          "Password": "password1234"
        }
      }
    }
  },
}