在.Net Core中使用Protobuf和.proto文件

时间:2017-01-09 08:52:46

标签: c# asp.net-core nancy protocol-buffers

我正在研究使用Protobuf在我的微服务之间发送数据,以及 我在Google.ProtoBuf而不是ProtoBuf-Net中使用C#支持,因为我想从.proto files编译类。

原因是微服务不是严格的.Net。其中一些是用Go等编写的。

我正在寻找包ProtoBufFormatter中的WebApiContrib.Formatting.ProtoBuf之类的内容,但支持Google.ProtoBuf

如果客户端已将内容类型设置为ProtoBufFormatter,则application/x-protobuf会返回序列化的protobuf数据,否则为Json

如何为Google.ProtoBuf实现类似的功能?此外,我也在研究在.Net Core上找到对Nancy Framework的这种支持。

我找到了这个link,它解释了如何在Protobuf-Net中使用protobuf文件,但似乎不是最新的(.Net Core + VSCode)。

1 个答案:

答案 0 :(得分:0)

我找不到Google.Protobuf的用例的任何解决方案,因此我在this博文中使用了自定义InputFormatterOutputFormatter,{{1 }}

然后,为了调用和反序列化客户端中的protobuf内容,我提出了这个解决方案:

Protobuf-Net

下一步将弄清楚如何使用 var client = new System.Net.Http.HttpClient { BaseAddress = new Uri("http://localhost:5002") }; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-protobuf")); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var response = await client.GetAsync("api/home"); if (response.IsSuccessStatusCode) { if (response.Content.Headers.ContentType.MediaType == "application/x-protobuf") { using(var stream = await response.Content.ReadAsStreamAsync()) { var protoBufModel = ProtoBuf.Serializer.Deserialize<ProtobufModelDto>(stream); return $"{protoBufModel.Name}, {protoBufModel.StringValue}, {protoBufModel.Id}"; } } var content = await response.Content.ReadAsStringAsync(); var jsonModel = JsonConvert.DeserializeObject<ProtobufModelDto>(content); return $"{jsonModel.Name}, {jsonModel.StringValue}, {jsonModel.Id}"; } return "Failed"; .proto文件创建模型。