javascript – Protobuf:WebApi – > JS – 解码对象为空

我想通过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);

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...