7

我想WebApi通过请求将对象从控制器发送到 Html 页面Ajax

当我在 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;
    }
    
    • 服务器代码:

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

      容器.Models.Add(model);

    • 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": []
      }
      
    • 字节缓冲区.js

    • protobuf.js v5.0.1
4

1 回答 1

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);
于 2016-03-29T13:12:30.493 回答