0

I have the following ASP.NET Core Controller:

using System.Text;
using Microsoft.AspNetCore.Mvc;

namespace FightClubApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProjectMayhemController : ControllerBase
    {
        [HttpGet]
        public Member Get() =>
            new Member
            {
                Name = "Robert Paulson",
                Code = ASCIIEncoding.ASCII.GetBytes("His name was Robert Paulson")
            };
    }

    public class Member
    {
        public string Name { get; set; }
        public byte[] Code { get; set; }
    }
}

Hitting that API endpoint (using GET https://localhost:5001/api/ProjectMayhem) returns the following JSON:

{
  "name": "Robert Paulson",
  "code": "SGlzIG5hbWUgd2FzIFJvYmVydCBQYXVsc29u"
}

However, I would like the Member.Code property to be serialized to a JavaScript Uint8Array.

I could convert the Base64 encoded JSON property back to a Uint8Array using something like:

code = new TextEncoder("utf-8").encode(atob(code));

, but I want to avoid doing it on the front-end.

4

1 回答 1

0

Code刚刚意识到如果我制作一个字节列表我可以做到这一点,即

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Mvc;

namespace FightClubApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProjectMayhemController : ControllerBase
    {
        [HttpGet]
        public Member Get() => new Member
        {
            Name = "Robert Paulson",
            Code = ASCIIEncoding.ASCII.GetBytes("His name was Robert Paulson")
                                      .ToList()
        };
    }

    public class Member
    {
        public string Name { get; set; }
        public List<byte> Code { get; set; }
    }
}

点击该 API 端点(使用 GET https://localhost:5001/api/ProjectMayhem)返回以下 JSON:

{
  "name": "Robert Paulson",
  "code": [
    72, 105, 115, 32, 110, 97, 109, 101, 32, 119, 97, 115, 32, 82, 111, 98, 101, 114, 116, 32, 80, 97, 117, 108, 115, 111, 110
  ]
}

我只需要将其转换为Uint8Array.

于 2019-10-24T16:18:04.787 回答