如何反序列化来自 HttpResponseMessage 的 protobuf 内容

How to deserialize protobuf content from HttpResponseMessage

我正在尝试反序列化来自我的数据库的 protobuf 格式的响应消息。它有这个架构:

syntax = "proto3";

message Person {
  uint64 id = 1;
  string name = 2;
  string surname = 3;
  uint32 age = 4;
};

我创建了这个 class 来反序列化它:

[ProtoContract]
public class Person
{
    [ProtoMember(1)]
    public long Id { get; set; }
    [ProtoMember(2)]
    public string Name { get; set; }
    [ProtoMember(3)]
    public string Surname { get; set; }
    [ProtoMember(4)]
    public int Age { get; set; }
}

接下来,我尝试这样做:

var response = await client.PostAsync("", new StringContent(request));
using (var responseStream = await response.Content.ReadAsStreamAsync())
{
    var person = Serializer.Deserialize<Person>(responseStream);
}

但我投了一个ProtoBuf.ProtoException: Invalid wire-type;

然后我决定看字节数组:

{25, 8, 1, 18, 6, 82, 111, 98, 101, 114, 116, 26, 11, 79, 112, 112, 101, 110, 104, 101, 105, 109, 101, 114, 32, 38 }

我手动创建了一个条目,它必须由我的数据库返回,并将其序列化:

{8, 1, 18, 6, 82, 111, 98, 101, 114, 116, 26, 11, 79, 112, 112, 101, 110, 104, 101, 105, 109, 101, 114, 32, 38 }

如您所见,它们几乎相同,但我的数据库在开始时发送 25

你能帮帮我吗,可能是什么错误? 谢谢!

我意识到,这是由于 streaming multiple messages。 在这种情况下,我将方法重写为:

List<Person> persons;
using (var responseStream = await response.Content.ReadAsStreamAsync())
{
    persons = Serializer.DeserializeItems<Person>(responseStream, PrefixStyle.Base128, 0).ToList();
}