HttpClient POST Protobuf ByteArray 到 ASP.NET Core Web API

HttpClient POST Protobuf ByteArray to ASP.NET Core Web API

我正在努力发送一些 protobuf 二进制数据以取回一些其他二进制数据。

代码如下:

客户:

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

服务器:

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

问题是它甚至没有到达服务器 Post 方法。它直接失败到 client.PostAsync 一个。我收到 Unsupported Media Type 错误:

我什至试过:

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

没用...

我找到的关于这个问题的所有答案要么是旧的 (This is the method I'm failing to apply),要么有一些奇怪的 Base64 字符串 Json 编码序列化 我绝对想避免...

还有一些 protobuf-net 相关的答案,但我想避免任何第三方包。

好的,终于找到解决办法了。问题出在控制器中。做法是:

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

使用方法:

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