Home > other >  net5.0 - Error receiving diferent size of byte array between Microservices
net5.0 - Error receiving diferent size of byte array between Microservices

Time:11-24

I have 2 Microservices (In a simple way to share it), here's the code from the "source" Microservice

    [HttpGet]
    [Route("resource")]
    public async Task<byte[]> LocateResource(Guid Id)
    {
        if (Id== Guid.Empty)
        {
            throw new Exception("Invalid Id");
        }

        var (content, message) = await _repo.LocateResource(Id);
        if (!message.Equals("Success"))
        {
            throw new Exception(message);
        }
        // content.lenght equivalent to 56129
        return content;
    }

and then Here is the code for the "Client"

    public async Task<byte[]> ReadFile2(Guid fileStorageId)
    {

        var response = await _httpClient.GetAsync($"{_urlOptions.Value.ReadFileEndpoint}?Id={Id}");
        response.EnsureSuccessStatusCode();
        var file = await response.Content.ReadAsByteAsync();

        // file.lenght equivalent to 74000
        return file;

}

The problem is that I'm sending 56129 bytes and I'm receiving 74000 bytes in the "Client", and it looks like there is no explanation for this behavior. Can someone give me further details, please?

CodePudding user response:

ReadAsByteAsync actually exist in HttpContent. I suggest you have a custom response class that handles conversion

CodePudding user response:

You should return response of type FileContentResult. For example:

using Microsoft.AspNetCore.Mvc;

namespace WebApplication2.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        [HttpGet("file")]
        public IActionResult GetFile()
        {
            var result = new byte[] { 1, 2, 3, 4, 5, 6, 7 };
            return this.File(result, "application/octet-stream");
        }
    }
}

File is a helper method defined in ControllerBase class.

By default ASP.NET serializes content to JSON and binary data is encoded using base64. That's why you get bigger response then you expect. The result from my example looks like this when encoded and serialized: "AQIDBAUGBw==".

  • Related