Protobuf: WebApi & # 8594; JS - decoded object is empty

I would like to send an object from a WebApi controller to an Html page through an Ajax request.

When I get the object in JS, it is empty. But on the server side, the object is not empty, because when I look at byte[].length , it is greater than 0.

  • On the server side, I use the dll provided by Google .
  • JS, I am using the ProtobufJS library . This is my .proto file:

     syntax="proto3"; message Container { repeated TestModel2 Models = 1; } message TestModel2 { string Property1 = 1; bool Property2 = 2; double Property3 = 3; } 
    • Server Code:

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

      container.Models.Add (model);

    • Base64 data:

    ChEKBFRlc3QQARkfhetRuB4JQA ==

    • JS decoding:

       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); 
    • The result object in the JS console:

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

    • protobuf.js v5.0.1
+7
javascript asp.net-web-api protocol-buffers
source share
1 answer

Finally, I solved the problem myself.

It was the client side that was to blame.

  • In fact, xhr.response is a JSON format, so it was between the double quotes "ChEKBFRlc3QQARkfhetRuB4JQA==" . I had to JSON. View my answer. enter code here
  • I deleted xhr.responseType = "arraybuffer";

Here is my code now:

 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); 
+2
source share

All Articles