Protobuf:WebApi - > JS - 解码对象为空

Gui*_*ume 7 javascript protocol-buffers asp.net-web-api protobuf.js

我想WebApi通过Ajax请求从控制器向Html页面发送一个对象.

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

  • 服务器端,我使用谷歌提供的DLL.
  • JS方面,我使用的是ProtobufJS库.这是我的.proto档案:

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

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

      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);
      
      Run Code Online (Sandbox Code Playgroud)
    • JS控制台中的结果对象:

      {
          "Models": []
      }
      
      Run Code Online (Sandbox Code Playgroud)
    • bytebuffer.js

    • protobuf.js v5.0.1

Gui*_*ume 2

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

是客户端出了问题。

  • 事实上,它xhr.response是 JSON 格式,因此它位于双引号之间"ChEKBFRlc3QQARkfhetRuB4JQA=="。我必须 JSON.parse 我的回复。enter code here
  • 我删除了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);
Run Code Online (Sandbox Code Playgroud)