如何序列化一个对象,但给定的 属性 保持序列化为字节数组?

How can I serialize an object but have a given property remain serialized to a byte array?

我有以下ASP.NET核心控制器:

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; }
    }
}

命中 API 端点(使用 GET https://localhost:5001/api/ProjectMayhem)returns 以下 JSON:

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

但是,我希望将 Member.Code 属性 序列化为 JavaScript Uint8Array.

我可以使用以下方法将 Base64 编码的 JSON 属性 转换回 Uint8Array

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

,但我想避免在前端做。

刚刚意识到,如果我制作 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)returns 以下 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