问题描述
我已经在.NET Core中创建了一个gRPC服务,该服务需要在.NET 4.7.2上运行的旧版WPF应用程序中使用.现有的WPF应用程序非常庞大,无法立即转换为.NET Core,仅使用gRPC付出的努力是不值得的.我的问题是,有没有一种方法可以使用.NET 4.7.2 WPF中的gRPC服务?
I have created a gRPC service in .NET Core which needs to be used from a legacy WPF application running on .NET 4.7.2. The existing WPF application is huge and can't be converted immediately to .NET Core and the effort isn't worth it just to use gRPC. My question is, is there a way to use the gRPC service from .NET 4.7.2 WPF?
推荐答案
我终于有了以下解决此问题的有效解决方案:
I finally got a working solution for this problem with:
- Asp .NET Core 3.1服务器(使用新的grpc-dotnet程序包)和
- .NET Framework 4.7.2 WPF客户端(使用旧的C包装器grpc包)
主要问题是找到一种解决方案来接受来自远程客户端的自签名SSL服务器证书,这对于我们的情况是必不可少的.
The main problem was to find a solution to accept a self-signed SSL server certificate from a remote client, which is a mandatory for our scenario.
服务器使用此处提供的解决方案获取生成的证书(该解决方案也适用于任何有效证书): https://gist.github.com/mivano/356d4f0354d997370e3c2e62809cdeef
The server gets a generated certificate using a solution like provided here (solution also works with any valid certificate):https://gist.github.com/mivano/356d4f0354d997370e3c2e62809cdeef
- 将Subject/FriendlyName调整为更有意义的内容
- 将DnsName调整为服务器的IP或主机名(客户端使用)
- 将NotAfter调整为所需的结束日期
- 调整后的$ pfxPassword
重要这里要提到的事情:服务器的DNS或IP已由客户端验证,因此它必须是证书的一部分.
Important thing to mention here: the DNS or IP of the server is verified by the client so it has to be part of the certificate.
以这种方式配置gRPC服务器(也可以通过.appsettings.json实现):
gRPC Server was configured this way (could also be achieved through .appsettings.json):
webBuilder.ConfigureKestrel(
options =>
{
options.Listen(
IPAddress.Any,
<your port>,
listenOptions =>
{
listenOptions.UseHttps("<your.pfx path>", "<your passphrase>");
listenOptions.Protocols = HttpProtocols.Http2;
});
});
gRPC客户端:
- 从您的.pfx文件创建一个.pem文件(使用openssl):
openssl pkcs12 -in "<pfx path>.pfx" -out "<pem path>.pem" -clcerts
- 读取客户端中的.pem文件并将其用于gRPC通道:
频道:
var channelCredentials = new SslCredentials(
File.ReadAllText("<path to pem>.pem"), null, verifyPeerCallback => true);
var serviceChannel = new Channel("<DnsName from cert", <port>, channelCredentials);
var serviceProxy = new GrpcService.GrpcServiceClient(serviceChannel );
还可以将客户端实现为使用可靠的HttpClient从服务器动态下载证书.使用适当的HttpClientHandler和附加的ServerCertifacteCustomValidationCallback获取.必须在创建服务通道之前在内存中创建pem: https://github.com/grpc/grpc/issues/8978#issuecomment- 283469676
The client can also be implemented to dynamically download the certificate from the server using a regualar HttpClient.Get with a proper HttpClientHandler and attached ServerCertifacteCustomValidationCallback. The pem has to be created in memory before the service channel creation:https://github.com/grpc/grpc/issues/8978#issuecomment-283469676
这篇关于如何从运行.NET 4.7.2的WPF访问gRPC服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!