简体   繁体   中英

Web Api convert byte array to base64 for every query

I have multiple methods where I return a query and the problem is that FileContent returns a byte array. I don't want to convert the byte array to base64 in every request I make. Is there a way to apply converting in every web api method so that I don't need to worry about that?

Before this, I saved every file as a base64 string in my db, but I read that it will consume more space than normaly. So I decided to change it to byte array but I dont know how to solve this problem.

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

You have several options:

  1. Extend your existing FileModel with a get-only property. You can also do this in a lazy-loaded fashion.
public byte[] FileContent { get; set; }
public string FileContentString { get { return Convert.ToBase64String(FileContent); } }
  1. Depending on the serializer you're using (eg Newtonsoft.Json), you can override the way properties are serialized. You can eg ignore or convert certain properties.

  2. Implement a custom 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)
        }
}

and then

public Base64Result Row([FromRoute] int id)
{
   // ...
   return new Base64Result(file);
}
  1. You can create a "view-model" with properties of the desired type, fill them, and use an automapper to take care of the rest of the properties.

There are plenty of options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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