![](/img/trans.png)
[英]Using C# HttpClient, how to POST a string HttpContent to 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之一。 我收到不支持的媒體類型錯誤:
我什至嘗試過:
content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
不工作...
我對這個問題找到的所有答案要么是舊的(這是我未能應用的方法),要么有一些奇怪的 Base64 字符串 Json 編碼序列化我絕對想避免......
還有一些與protobuf-net相關的答案,但我想避免使用任何第三方 package。
好的,終於找到解決方案了。 問題出在 controller 中。 做法是:
[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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.