在服务器端C#中读取grpc中的元数据

时间:2019-02-15 16:46:31

标签: c# .net-core metadata grpc proto

我正在从客户端发送元数据中的令牌

      Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure);
  ItemQuery item = new ItemQuery() { Id = "abc" };
  var client = new MyService.MyServiceClient(channel);
  Metadata data = new Metadata
  {
    { "token", "Bearer xhrttt" }
  };
  var reply = client.GetItem(item, data);

但是无法找到在服务器端获取它的方法,感谢您的帮助

以下是我的服务器端代码外观的示例(我也尝试了其他某些方式)

public override Task<ItemResponse> GetItem(ItemQuery request , ServerCallContext context)
    {
        try
        {
            var a = context.RequestHeaders["token"]; // not working 
            ItemResponse itmRes = new ItemResponse();
            if (request.Id == "foo")
            {
                itmRes.Items.Add(new Item() { Id = "foo", Name = "foobar" });
            }
            return Task.FromResult(itmRes);
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
        return null;
    }

1 个答案:

答案 0 :(得分:1)

下面是在c#中获取元数据的代码

                Metadata.Entry metadataEntry = context.RequestHeaders.FirstOrDefault(m =>
            String.Equals(m.Key, "token", StringComparison.Ordinal));

            if (metadataEntry.Equals(default(Metadata.Entry)) || metadataEntry.Value == null)
            {
                return null;
            }
            Console.WriteLine("Token value is {0}", metadataEntry.Value);

有关更多详细信息,请参见https://csharp.hotexamples.com/examples/Grpc.Core/ServerCallContext/-/php-servercallcontext-class-examples.html