【问题标题】:How to call self-signed gRPC service from Xamarin.Forms (iOS and Android)如何从 Xamarin.Forms(iOS 和 Android)调用自签名 gRPC 服务
【发布时间】:2021-05-15 16:16:52
【问题描述】:

我正在尝试从 Xamarin.Forms 应用程序调用使用 .NET 5 上的 ASP.NET Core 构建的 gRPC 服务。

我在服务器端使用 Grpc.AspNetCore 2.35.0,在应用程序库 (.NETStandard 2.1) 中使用 Grpc.Net.Client 2.35.0。

当尝试从客户端调用服务时,我得到一个异常:

Exception caught: MyException: An unknown error happened
---> Grpc.Core.RpcException: Status(StatusCode="Internal", Detail="Error starting gRPC call. HttpRequestException: The SSL connection could not be established, see inner exception. AuthenticationException: Authentication failed, see inner exception. TlsException: CertificateUnknown", DebugException="System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
---> System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception.
---> Mono.Security.Interface.TlsException: CertificateUnknown
  at Mono.AppleTls.AppleTlsContext.EvaluateTrust () [0x000bf] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/System/Mono.AppleTls/AppleTlsContext.cs:306 
[… SNIP …]

我认为这与自签名证书有关。我正在使用使用dotnet dev-certs https 工具创建的生成的开发证书。

我尝试按照here 的建议向创建的频道添加自定义处理程序:

GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions
{
    HttpHandler = new HttpClientHandler
    {
        ServerCertificateCustomValidationCallback =
            HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
    }
});

还有另一个建议:

AppContext.SetSwitch(
    "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
GrpcChannel.ForAddress("http://localhost:5000");

但是这两种方法都会导致另一个异常(可能是因为这将使用不支持 HTTP/2.0 的旧 HttpClientHandler 实现):

Exception caught: MyException: An unknown error happened
---> Grpc.Core.RpcException: Status(StatusCode="Internal", Detail="Request protocol 'HTTP/1.1' is not supported.")

我还尝试通过创建自定义 CA plus 证书并在 iOS 模拟器中安装该根证书来规避自签名证书。但同样的结果发生了。我不确定它是否会对 Android 产生影响,因为我无法在模拟器上安装根证书。

如何将 gRPC 与 Xamarin.Forms 一起用于开发服务器?

【问题讨论】:

    标签: c# asp.net-core xamarin grpc


    【解决方案1】:

    我已经修复了他上面的异常,改变了我的实现以匹配这个:https://techblog.livongo.com/implementing-grpc-in-a-xamarin-mobile-project/ 块。

    更多细节:

    • 我添加了对 Grpc.Core、Grpc.Tools、Grpc.Net.Common、Grpc.Net.Client、Grpc.Core.Api 的引用;

    • 我在创建频道时添加了这段代码:

       var credentials = CallCredentials.FromInterceptor((context, metadata) => Task.CompletedTask);
       return new Channel("<your domai>:<port>", ChannelCredentials.Create(new SslCredentials(), credentials));
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-18
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 2017-04-10
      • 2015-09-19
      • 2018-07-28
      相关资源
      最近更新 更多