我在推测如何从web接收干净的字节数组(在base64中没有编码/解码)。我还是不知道这是否可能。可能有些事情我做错了,或者我还不知道。我创造了一个简单的例子来解释这个问题。如您所见,我只是试图发送一个以字节数组编码的文本字符串,并在客户端对其进行解码。
后端,一个最小的API
using System.Net;
using System.Net.Http.Headers;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/GetQuote", () => HttpBinaryDataTest.GetQuote());
app.Run();
class HttpBinaryDataTest
{
public static HttpResponseMessage GetQuote()
{
var text = "I became insane, with long intervals of horrible sanity.";
var bytes = Encoding.UTF8.GetBytes(text);
var response = new HttpResponseMessage(HttpStatusCode.OK) {
Content = new ByteArrayContent(bytes)
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
}
}前端测试,控制台应用程序
using System.Text;
Console.WriteLine("Http Binary Test");
Console.WriteLine("Press any key to start...");
Console.ReadKey();
var h = new HttpTest();
var quote = await h.GetQuote();
Console.WriteLine(quote);
Console.WriteLine("Press any key to end...");
Console.ReadKey();
h.Dispose();
// -------------------------------------------------------
class HttpTest : IDisposable
{
string apiRoot = "http://localhost:5274/"; // ApiTest
readonly HttpClient client;
public HttpTest()
{
client = new HttpClient {
BaseAddress = new Uri(apiRoot)
};
}
public async Task<string> GetQuote()
{
var response = await client.GetAsync($"GetQuote");
var bytes = await response.Content.ReadAsByteArrayAsync();
var decodedText = Encoding.UTF8.GetString(bytes);
// Should be:
// I became insane, with long intervals of horrible sanity.
return decodedText;
}
public void Dispose() => client?.Dispose();
}当我运行客户机时,我得到的是一个JSON,没有错误,但我不知道如何获得我期望的数据。我遗漏了什么?我做错了什么?答复:
{
"version": "1.1",
"content": {
"headers": [{
"key": "Content-Type",
"value": ["application/octet-stream"]
}
]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"trailingHeaders": [],
"requestMessage": null,
"isSuccessStatusCode": true
}发布于 2022-05-29 07:05:39
您可以通过如下编辑服务器代码来完成这一任务:
using System.IO;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/GetQuote", () => Results.Stream(HttpBinaryDataTest.GetQuote()));
app.Run();
class HttpBinaryDataTest
{
public static MemoryStream GetQuote()
{
var text = "I became insane, with long intervals of horrible sanity.";
var bytes = Encoding.UTF8.GetBytes(text);
var ms = new MemoryStream(bytes);
return ms;
}
}控制台应用程序的执行结果是
Http二进制测试按任意键开始.我疯了,长时间的可怕的精神错乱。按任意键结束..。
在您的代码示例中,最小的API将您要创建的HTTP响应作为HTTP响应的主体。所以不是正确的方法。我用邮递员来测试,这样就更容易发现了。
由于您需要二进制或我们称之为流,所以查看MS文档中的最小API,我发现了以下内容:https://learn.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0#stream
https://stackoverflow.com/questions/72421011
复制相似问题