因为Grpc采用HTTP/2作为通信协议,默认采用LTS/SSL加密方式传输,比如使用.net core启动一个服务端(被调用方)时:  

    public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.ConfigureKestrel(options =>
{
options.ListenAnyIP(5000, listenOptions =>
{
listenOptions.Protocols = HttpProtocols.Http2;
listenOptions.UseHttps("xxxxx.pfx", "password");
});
});
webBuilder.UseStartup<Startup>();
});

  其中使用UseHttps方法添加证书和秘钥。

  但是,有时候,比如开发阶段,我们可能没有证书,或者是一个自己制作的临时测试证书,那么在客户端(调用方)调用是可能就会出现下面的异常:  

  Call failed with gRPC error status. Status code: 'Internal', Message: 'Error starting gRPC call. HttpRequestException: The SSL connection could not be established, see inner exception. AuthenticationException: The remote certificate is invalid according to the validation procedure.'.
  fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
  Grpc.Core.RpcException: Status(StatusCode="Internal", Detail="Error starting gRPC call. HttpRequestException: The SSL connection could not be established, see inner exception. AuthenticationException: The remote certificate is invalid according to the validation procedure.", DebugException="System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
  ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
at System.Net.Security.SslStream.StartSendAuthResetSignal(ProtocolToken message, AsyncProtocolRequest asyncRequest, ExceptionDispatchInfo exception)
at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartReceiveBlob(Byte[] buffer, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartSendBlob(Byte[] incoming, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.ProcessReceivedBlob(Byte[] buffer, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.StartReadFrame(Byte[] buffer, Int32 readBytes, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslStream.PartialFrameCallback(AsyncProtocolRequest asyncRequest)
--- End of stack trace from previous location where exception was thrown ---
at System.Net.Security.SslStream.ThrowIfExceptional()
at System.Net.Security.SslStream.InternalEndProcessAuthentication(LazyAsyncResult lazyResult)
at System.Net.Security.SslStream.EndProcessAuthentication(IAsyncResult result)
at System.Net.Security.SslStream.EndAuthenticateAsClient(IAsyncResult asyncResult)
  ..........

  然而我们可能没有办法得到有效的证书,这时,我们有两个办法:

  1、使用http协议

  想想,我们为什么要使用Grpc?因为高性能,高效率,简单易用吧,但是https相比http就是多个加密的过程,这可能会有一定的性能损失(一般可忽略)。

  而一般的,我们在微服务架构中使用Grpc比较多,而微服务一般部署在我们自己的一个子网下,这也就没必要使用https了吧?

  具体可参考我上一篇:.net core中Grpc使用报错:The response ended prematurely.

  2、调用时不对证书进行验证

  如果是控制台程序,我们可以这么做:  

    public static void Main(string[] args)
{
var channel = GrpcChannel.ForAddress("https://localhost:5000", new GrpcChannelOptions()
{
HttpClient = null,
HttpHandler = new HttpClientHandler
{
//方法一
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
//方法二
//ServerCertificateCustomValidationCallback = (a, b, c, d) => true
}
}); var client = new Greeter.GreeterClient(channel);
var result = client.SayHello(new HelloRequest() { Name = "Grpc" });
}

  其中 HttpClientHandler 的 ServerCertificateCustomValidationCallback 是对证书的自定义验证,上面给出了两种方式验证。

  如果是.net core的webmvc或者webapi程序,因为.net core 3.x开始已经支持了Grpc的引入,所以我只需要在ConfigureServices中注入Grpc的客户端是进行设置:  

    public void ConfigureServices(IServiceCollection services)
{
services.AddGrpcClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient), options =>
{
options.Address = new Uri("https://localhost:5000");
}).ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
//方法一
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
//方法二
//ServerCertificateCustomValidationCallback = (a, b, c, d) => true
};
}); ...
}

  因为.net core3.x中Grpc的使用是基于它的HttpClient机制,比如 AddGrpcClient 方法返回的就是一个 IHttpClientBuilder 接口对象,上面的配置我们还可以这么写:  

    public void ConfigureServices(IServiceCollection services)
{
services.AddGrpcClient<Greeter.GreeterClient>(nameof(Greeter.GreeterClient));
services.AddHttpClient(nameof(Greeter.GreeterClient), httpClient =>
{
httpClient.BaseAddress = new Uri("https://localhost:5000");
}).ConfigurePrimaryHttpMessageHandler(() =>
{
return new HttpClientHandler
{
//方法一
ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
//方法二
//ServerCertificateCustomValidationCallback = (a, b, c, d) => true
};
}); ...
}

  总之,不管怎么调用,机制都是一样的,最终都是像上面的客户端调用一样去创建Client,只要能理解就好了。

最新文章

  1. SWFUpload多图上传、C#后端跨域传文件带参数
  2. dojo tree edit的使用[前端]
  3. Slyx_SerAddGet
  4. 创建MySQL用户 赋予某指定库表的权限 flush privileges才能生效!!!!;@&#39;localhost&#39;授权本地,@&#39;%&#39;授权远程
  5. oracle数据库sql的基本使用
  6. Asp.Net运行原理(=)
  7. POJ_3258_River_Hopscotch_[NOIP2015]_(二分,最大化最小值)
  8. HDOJ 1237题 简单计算器
  9. Android添加桌面快捷方式的简单实现
  10. iOS程序发布时出现your application is being uploaded解决办法
  11. Hibernate 系列教程17-查询缓存
  12. GitLab Wiki 内容恢复版本管理
  13. 移动端二三事【三】:transform的注意事项
  14. 不可思议的混合模式 background-blend-mode
  15. conn.go 源码阅读
  16. submit form to convert to a Java Bean model.
  17. scope 前缀开头的方法
  18. QT编译错误: multiple definition of `qMain(int, char**)&#39;
  19. Spring Boot热部署(springloader)
  20. RabbitMQ 远程 IP 访问 解决办法 -摘自网络

热门文章

  1. OpenStack之三: 安装MySQL,rabbitmq, memcached
  2. CentOS 6.4 下 Python 2.6 升级到 2.7
  3. 【编程思想】【设计模式】【结构模式Structural】3-tier
  4. typora使用快捷键
  5. 使用jquery完成抽奖图片滚动的效果
  6. 【C/C++】二维数组的传参的方法/二维字符数组的声明,使用,输入,传参
  7. Istio在Rainbond Service Mesh体系下的落地实践
  8. Python 的切片为什么不会索引越界?
  9. LuoguP7080 [NWRRC2013]Ballot Analyzing Device 题解
  10. java 多线程 线程池:多核CPU利用ExecutorService newWorkStealingPool; ForkJoinPool线程池 执行可拆分的任务RecursiveAction;RecursiveTask