【发布时间】:2021-03-30 10:59:32
【问题描述】:
我想使用 Enum 或类似方法为我的 gRPC 服务器定义这样的路由器或映射
我有一个名为 ServerHubService 的简单服务和一个 Hubs 文件夹,其中包含一些类,这些类将处理每个请求将由客户端传递到我的 gRPC 服务器
这是我的项目的屏幕截图 Project Structure 现在可以在照片中看到 文件内容也是下图 HubMap.cs
如您所见,我想定义一个 switch case 语句来运行不同的类
这是我的 ServiceHubService gRPC 类 ServerHubService.cs
最后这是我的客户端调用grpc-client.cs
Visual Studio 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;
}
我的 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)
}) ;
}
}
}
和 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"
};
}
}
问题 2:
如何检测 proto 文件中定义的枚举和 HubMap.cs 中的进程
【问题讨论】:
-
这里的主要问题似乎只是您没有使用
async;那应该是public async Task<string> CustomMethodAsync(...)或public async ValueTask<string> CustomMethodAsync(...),不是吗? -
不,我得到错误'无法从 HubMap.HubSelector 转换为字符串
-
您还在
ActionManager中显示了一些由于“明确分配”(selector)造成的损坏代码;如果你能问一个具体的问题,说明你在问什么问题,那就太好了;特别是,说出您要询问的编译器错误(红色波浪线) -
"不,我得到错误 ' 无法从 HubMap.HubSelector 转换为字符串" - 我们已经猜到了,到底是怎么回事?这正是我说要明确的原因;现在;我们看不到你的
ActionRequest类型,所以......在这里帮助我们;ActionRequest.ActionType是否定义为string?并且:应该是吗? -
此外,将所有代码显示为问题中的文本,而不是屏幕截图,会有所帮助...