如何从HttpResponseMessage反序列化protobuf内容

时间:2019-03-25 19:05:35

标签: c# protobuf-net

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

syntax = "proto3";

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

我创建了该类以反序列化它:

[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

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

1 个答案:

答案 0 :(得分:0)

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

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