[英]HttpClient POST Protobuf ByteArray to ASP.NET Core Web API
I am struggling to send some protobuf binary data to get back some other binary data.我正在努力发送一些 protobuf 二进制数据以取回一些其他二进制数据。
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.问题是它甚至没有到达服务器Post方法。 It fails directly to the client.PostAsync one.
它直接失败到client.PostAsync之一。 I get the Unsupported Media Type error:
我收到不支持的媒体类型错误:
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...我对这个问题找到的所有答案要么是旧的(这是我未能应用的方法),要么有一些奇怪的 Base64 字符串 Json 编码序列化我绝对想避免......
There also are some protobuf-net related answer but I want to avoid any thirdparty package.还有一些与protobuf-net相关的答案,但我想避免使用任何第三方 package。
Ok, finally got to find the solution.好的,终于找到解决方案了。 Issue was in the controller.
问题出在 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.