0

I am struggling to send some protobuf binary data to get back some other binary data.

The code is the following:

Client:

HttpClient client = new HttpClient
{
    BaseAddress = new Uri("https://localhost:44302/")
};

// "Credentials" is a proto message
Credentials cred = new Credentials()
{
    Email = "my@email.com",
    Password = "mypassword"
};

var content = new ByteArrayContent(cred.ToByteArray());
var response = await client.PostAsync("api/database", content);

Server:

[HttpPost]
public async Task<IActionResult> Post(ByteArrayContent data)
{
    Credentials c = Credentials.Parser.ParseFrom(await data.ReadAsByteArrayAsync());

    // Get user from database, etc, etc...

    // "user" being another proto defined message
    return File(user.ToByteArray(), "application/octet-stream");
}

The thing is it doesn't even get to the server Post method. It fails directly to the client.PostAsync one. I get the Unsupported Media Type error: Unsupported Media Type

I even tried the:

content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");

Doesn't work...

All the answers I find to this issue are either old (This is the method I'm failing to apply) or have some weird Base64 string Json encoded serialization I absolutely want to avoid...

There also are some protobuf-net related answer but I want to avoid any thirdparty package.

loyd.f
  • 163
  • 1
  • 11

1 Answers1

1

Ok, finally got to find the solution. Issue was in the controller. Way to do is:

[HttpPost]
public async Task<IActionResult> LogIn()
{
    Credentials cred = Credentials.Parser.ParseFrom(Utils.ReadRequestBody(Request));
    // Use cred...
}

with method:

public static byte[] ReadStream(in Stream input)
{
    using (MemoryStream ms = new MemoryStream())
    {
        input.CopyTo(ms);
        return ms.ToArray();
    }
}

public static byte[] ReadRequestBody(in HttpRequest request)
{
    using (Stream stream = request.BodyReader.AsStream()) // Package "System.IO.Pipelines" needed here
    {
        return ReadStream(stream);
    }
}
loyd.f
  • 163
  • 1
  • 11