首页 > 解决方案 > Byte array from backend is converted to something else on front-end

问题描述

[Route("encrypted")]
[HttpGet]
public sbyte[] Encrypted()
{
    var mm = System.IO.File.ReadAllBytes("C:\\test\\" + "fill.txt");
    sbyte[] sbt = new sbyte[mm.Length];
    Buffer.BlockCopy(mm, 0, sbt, 0, mm.Length);
    return sbt;
}

when I hover over with mouse it shows following bytes (which is correct): enter image description here

But when I check on the front-end (javascript). It becomes a different arrayBuffer:

enter image description here

Here is the front end code:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/api/encrypted/', true);
xhr.responseType = 'arraybuffer'; //i have tried without this line too
xhr.onload = function (e) {
    if (this.status === 200) {
        console.log("received from server--------");
        console.log(e.currentTarget.response);
        console.log("received from server-------");
    }
};

xhr.send();

标签: javascriptc#asp.net-web-apiasp.net-core

解决方案


您没有提出具体问题,但我认为这可能会有所帮助。

您的控制器操作正在响应 JSON。转储json到控制台会在前端显示与转储sbt到后端控制台相同的数组值。这是转储值的前端代码。

var xhr = new XMLHttpRequest();
xhr.open('GET', '/api/values', true);
xhr.responseType = 'json';
xhr.onload = function (e) {
    if (this.status === 200) {
        console.log("json");
        const json = e.currentTarget.response;
        console.log(json);
        console.log("json");
    }
};

因此,您正在发送一个 JSON 数组。

顺便说一句,这里有一些关于arraybuffer响应类型的链接。


推荐阅读