我想通过Ajax请求从WebApi控制器向
Html页面发送一个对象.
当我在JS中收到对象时,它是空的.但是服务器端的对象不是空的,因为当我查看byte []时,它的长度大于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我的response.enter代码
>我删除了xhr.responseType =“arraybuffer”;
这是我现在的代码:
- var ProtoBuf = dcodeIO.ProtoBuf;
- var xhr = ProtoBuf.Util.XHR();
- xhr.open(
- /* method */ "GET",/* 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);