【问题标题】:Using Protobuf in .Net Core with .proto files在 .Net Core 中使用带有 .proto 文件的 Protobuf
【发布时间】:2017-05-23 11:39:58
【问题描述】:

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

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

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

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

我怎样才能为Google.ProtoBuf 实现类似的功能?此外,我还在寻找这种对 .Net Core 上的 Nancy Framework 的支持。

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

【问题讨论】:

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


    【解决方案1】:

    我无法使用Google.Protobuf 为我的用例找到任何解决方案,因此我使用了this 博客文章中的自定义InputFormatterOutputFormatter 以及Protobuf-Net

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

            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";
    

    下一步将弄清楚如何使用 Protobuf-Net.proto 文件创建模型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多