.net - WPF 桌面应用程序中的 gRPC 服务器?

标签 .net asp.net-core grpc

我目前正在研究 gRPC,到目前为止已经创建了一个简单的 C# hello world 演示,使用 Visual Studio ASP.Net Core gRPC Service 项目作为服务器,并使用客户端控制台应用程序.

我接下来要做的是让 gRPC 服务器在 .Net 6 WPF 桌面应用程序(称为“AppA”)中运行,允许另一个桌面应用程序(“AppB”)向 AppA 发出信息请求。这可能吗?

通常我会为此使用 WCF,但由于 CoreWCF 不成熟,我被警告不要使用它。

最佳答案

我找到了一种在 WPF 桌面应用程序中托管 gRPC 服务的方法。

项目需要引用“Grpc.AspNetCore”包(没有“proto”的东西,稍后你会明白为什么)。

然后是启动网络应用程序的代码。出于我的演示应用程序的目的,我在 MainWindow.xaml.cs 中实现了它:

private WebApplication? _app;

public MainWindow()
{
    InitializeComponent();
    Task.Run(() => StartServer());
}

private void StartServer()
{
    var builder = WebApplication.CreateBuilder();

    // Despite adding a "launchSettings.json" file to the project, I couldn't find a way 
    // for the builder to pick it up, so had to configure the URLs here:
    builder.WebHost.UseUrls("http://*:5219", "https://*:7219");

    builder.Services.AddGrpc();

    _app = builder.Build();
    _app.MapGrpcService<TestService>();
    _app.Run();
}

private void MainWindow_OnClosing(object? sender, CancelEventArgs e)
{
    _app?.StopAsync();
}

对 _app.Run() 的调用阻塞(直到 Web 应用程序停止),因此我在 b/g 线程上调用 StartServer()。

我发现一篇文章指出原型(prototype)编译器在 WPF 项目中无法正常工作。虽然它正在生成类,但构建错误表明找不到这些类。 解决方案是将“protos”内容和服务类添加到类库中,然后从 WPF“服务器”中引用它。类库项目需要引用以下包:

  • Google.Protobuf
  • Grpc.AspNetCore
  • Grpc.Tools

关于.net - WPF 桌面应用程序中的 gRPC 服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74151894/

相关文章:

ios - xcode9中grpc报错GPR_UNREACHABLE_COD如何修正

.net - RichTextBox 不显示 ' 并显示一个菱形,而不是里面有一个问号

c# - 在 linq 中添加带有计数函数的额外列以进行查询?

azure - 使用 Azure Devops 将 ASP.NET Core Web 应用程序部署到本地 IIS 的正确方法

go - 如何使用类型 func(*dialOptions)

grpc - 云任务创建 : Error: 3 INVALID_ARGUMENT: Request contains an invalid argument

c# - 为什么在隐藏方法时使用 "new"?

c# - 如何将标签的可见性属性绑定(bind)到多个RadioButton?

c# - 如何使用 WebRequest 访问使用 HTTPS 的 SSL 加密站点?

c# - 创建使用服务的新 AuthorizationHandler/IAuthorizationRequirement