繁体   English   中英

Web Api 为每个查询将字节数组转换为 base64

[英]Web Api convert byte array to base64 for every query

我有多种返回查询的方法,问题是 FileContent 返回一个字节数组。 我不想在我提出的每个请求中将字节数组转换为 base64。 有没有办法在每个 web api 方法中应用转换,这样我就不用担心了?

在此之前,我将每个文件都保存为我的数据库中的 base64 字符串,但我读到它会比平时消耗更多的空间。 所以我决定将其更改为字节数组,但我不知道如何解决这个问题。

public class File
{
    public int FileId { get; set; }

    public string FileName { get; set; }

    public byte[] FileContent { get; set; }

    public Advertentie Advertentie { get; set; }

    public int AdvertentieId { get; set; }

}

public IActionResult Row([FromRoute] int id)
{
    var advertentie = db.Advertenties.Include(x => x.Files).Where(a => a.Id == id).FirstOrDefault();
    // So here each advertentie can contain multiple files, how to convert FileContent to base64 so that every file becomes base64 and return advertentie.
    if(advertentie == null)
    {
        return NotFound();
    }
    return Ok(advertentie);
}

你有几个选择:

  1. 使用 get-only 属性扩展您现有的FileModel 您也可以以延迟加载的方式执行此操作。
public byte[] FileContent { get; set; }
public string FileContentString { get { return Convert.ToBase64String(FileContent); } }
  1. 根据您使用的序列化程序(例如 Newtonsoft.Json),您可以覆盖属性的序列化方式。 例如,您可以忽略转换某些属性。

  2. 实现自定义ActionResult

public class Base64Result : ActionResult
{
        private File _file;
        public Base64Result(File file)
        {
           _file = file;
        }

        public override async Task ExecuteResultAsync(ActionContext context)
        {            
            // Do the bas64 magic here (use _file to build a response)
        }
}

接着

public Base64Result Row([FromRoute] int id)
{
   // ...
   return new Base64Result(file);
}
  1. 您可以使用所需类型的属性创建“视图模型”,填充它们,然后使用自动映射器来处理属性的rest

有很多选择。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM