如何在 Grpc 请求中传递枚举

Sec*_*ity 4 c# grpc

我想使用 Enum 或类似方法为我的 gRPC 服务器定义这样的路由器或映射

我有一个名为 ServerHubService 的简单服务和一个 Hubs 文件夹,其中包含一些类,这些类将处理客户端将传递到我的 gRPC 服务器的每个请求

这是我的项目的屏幕 截图, 现在可以在照片中看到该文件的内容也是 HubMap.cs下面的图像

正如你所看到的,我想定义一个 switch case 语句来运行不同的类

这是我的 ServiceHubService gRPC 类 ServerHubService.cs

最后这是我的客户端调用grpc-client.cs

视觉工作室 2019 版本 16.10

这是我的 ServerHub.proto 文件:

syntax = "proto3";

option csharp_namespace = "NetPlus.Server.Core";

package server;


service ServereHub  {

rpc ActionManager (ActionRequest) returns (ActionResult);

}

message ActionRequest {
    string ActionType = 1;
}

message ActionResult {
    string ActionResultType = 1;
}
Run Code Online (Sandbox Code Playgroud)

我的 ServerHubService.cs :

using Microsoft.Extensions.Logging;
using NetPlus.Server.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using NetPlus.Server.Core.Hubs;
namespace NetPlus.Server.Core
{
    public class ServerHubService : ServereHub.ServereHubBase
    {
        private readonly ILogger<ServerHubService> _logger;

       public ServerHubService(ILogger<ServerHubService> logger)
        {
            _logger = logger;
        }

        public override Task<ActionResult> ActionManager(ActionRequest request, ServerCallContext context)
        {
            HubMap map = new HubMap();
            HubMap.HubSelector selector;

         
            return Task.FromResult(new ActionResult
            {
                ActionResultType = map.HubProccessor(selector)
            }) ;
        }
    }
    
}
Run Code Online (Sandbox Code Playgroud)

和 Hubmap.cs

using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace NetPlus.Server.Core.Hubs
{
    public class HubMap
    {
        Switcher switcher = new Switcher();

        public string HubNameResult { get; set; }
        public   enum HubSelector
        {
            SwitchServer_Off  = 1

        }
       
        public  string HubProccessor(HubSelector hName) =>
          
        
            hName switch
            {
                HubSelector.SwitchServer_Off => switcher.PutOffline(),
               
                _=> "Error Proccesing  Hub"
            };
        
        
    }

}
Run Code Online (Sandbox Code Playgroud)

问题2:这个错误是什么 在此输入图像描述

问题2:

如何检测 proto 文件中定义的枚举以及 HubMap.cs 中的进程

Mar*_*ell 6

如果您想通过 gRPC 传递枚举:用 gRPC 术语定义枚举:

syntax = "proto3";

option csharp_namespace = "NetPlus.Server.Core";

package server;

enum ActionType
{   // whatever contents...
    Foo = 0;
    Bar = 1;
    Blap = 2;
}
enum ActionResultType
{
    // ... etc
}
service ServereHub  {
   rpc ActionManager (ActionRequest) returns (ActionResult);
}

message ActionRequest {
    ActionType Action = 1;
}

message ActionResult {
    ActionResultType Result = 1;
}
Run Code Online (Sandbox Code Playgroud)

并使用生成的枚举。如果您不想这样做并想使用string:那么所有前后的转换都取决于您ToString()Enum.Parse你的朋友。