javascript - Protocol Buffer : WebApi -> JS - Decoded object is empty

标签 javascript asp.net-web-api protocol-buffers protobuf.js

我想通过 Ajax 请求将对象从 WebApi Controller 发送到 Html 页面。

当我在 JS 中收到对象时,它是空的。但是服务器端对象不是空的,因为当我查看 byte[].length 时它大于 0。

  • 服务器端,我使用 dll provided by Google .
  • JS 端,我使用 ProtobufJS library .这是我的 .proto 文件:

    syntax="proto3";
    
    message Container {
        repeated TestModel2 Models = 1;
    }
    
    message TestModel2 {
        string Property1 = 1;
        bool Property2 = 2;
        double Property3 = 3;
    }
    
    • 服务器代码:

      var container = new Container();
      
      var model = new TestModel2
      {
          Property1 = "Test",
          Property2 = true,
          Property3 = 3.14
      };
      

      container.Models.Add(模型);

    • Base64 数据:

    ChEKBFRlc3QQARkfhetRuB4JQA==

    • JS解码:

      var ProtoBuf = dcodeIO.ProtoBuf;
      var xhr = ProtoBuf.Util.XHR();
      xhr.open(
          /* method */ "GET",
          /* file */ "/XXXX/Protobuf/GetProtoData",
          /* async */ true
      );
      xhr.responseType = "arraybuffer";
      xhr.onload = function (evt) {
          var testModelBuilder = ProtoBuf.loadProtoFile(
              "URL_TO_PROTO_FILE",
              "Container.proto").build("Container");
          var msg = testModelBuilder.decode64(xhr.response); 
          console.log(JSON.stringify(msg, null, 4)); // Correctly decoded
      }
      xhr.send(null);
      
    • JS 控制台中的结果对象:

      {
          "Models": []
      }
      
    • bytebuffer.js

    • protobuf.js v5.0.1

最佳答案

最后我自己解决了这个问题。

是客户端出了问题。

  • 事实上 xhr.response 是 JSON 格式,所以它在双引号 "ChEKBFRlc3QQARkfhetRuB4JQA==" 之间。我必须对我的回复进行 JSON.parse。在此处输入代码
  • 我删除了 xhr.responseType = "arraybuffer";

这是我的代码:

var ProtoBuf = dcodeIO.ProtoBuf;
var xhr = ProtoBuf.Util.XHR();
xhr.open(
    /* method */ "GET",
    /* file */ "/XXXX/Protobuf/GetProtoData",
    /* async */ true
);
// xhr.responseType = "arraybuffer"; <--- Removed
xhr.onload = function (evt) {
    var testModelBuilder = ProtoBuf.loadProtoFile(
        "URL_TO_PROTO_FILE",
        "Container.proto").build("Container");
    var msg = testModelBuilder.decode64(JSON.parse(xhr.response)); <-- Parse the response in JSON format
    console.log(msg); // Correctly decoded
}
xhr.send(null);

关于javascript - Protocol Buffer : WebApi -> JS - Decoded object is empty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36173864/

相关文章:

javascript - 如何在 javascript 中将这两个数组组合成一个 3d 数组

启用了 CORS 的 c# Web Api 并且请求的资源上存在可怕的 No 'Access-Control-Allow-Origin' header

go - 为 protobuf 扩展指定 JSON 名称

c# - 从 C# 读取 protobuf3 自定义选项

javascript - 单击按钮时无法更改输入框的值

javascript - NVelocity 高级循环语法

javascript - 强连通分量算法

c# - 如何将位图返回给浏览器 WebApi

c# - WebAPI Controller GetAll 或 Get some Id

protocol-buffers - 如何确定 Protobuf 对象的 protobuf 版本?