简体   繁体   English

从 REST 服务获取 base64 中无编码/解码的字节数组 - 可能吗?

[英]Get a byte array no encode/decode in base64 from REST Service - It's possible?

I was speculating how to receive a clean byte array from a web-api (no encode/decode in base64).我在猜测如何从 web-api 接收一个干净的字节数组(base64 中没有编码/解码)。 I still don't know if this is possible.我仍然不知道这是否可能。 Possibly there are things that I am doing wrong, or that I don't know yet.可能有些事情我做错了,或者我还不知道。 I have created a simple example to explain the issue.我创建了一个简单的例子来解释这个问题。 As you can see I'm just trying to send a text string encoded in a byte array, and decode it on the client side.如您所见,我只是想发送一个以字节数组编码的文本字符串,并在客户端对其进行解码。

Backend, a minimal API后端,最小的 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;
    }
}

Frontend Test, a console application前端测试,一个控制台应用程序

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


When I run the client, what I get is a JSON, without errors, but I don't know how to get the data I expect.当我运行客户端时,我得到的是一个 JSON,没有错误,但我不知道如何获取我期望的数据。 What am I missing?我错过了什么? What am I doing wrong?我究竟做错了什么? The response:响应:

 {
"version": "1.1",
"content": {
    "headers": [{
            "key": "Content-Type",
            "value": ["application/octet-stream"]
        }
    ]
},
"statusCode": 200,
"reasonPhrase": "OK",
"headers": [],
"trailingHeaders": [],
"requestMessage": null,
"isSuccessStatusCode": true
}

You can do it by editing the server code as follow:您可以通过编辑服务器代码来做到这一点,如下所示:

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

The console app execution result was控制台应用程序执行结果是

Http Binary Test Press any key to start... I became insane, with long intervals of horrible sanity. Http Binary Test 按任意键开始...我变得精神错乱,长时间处于可怕的理智状态。 Press any key to end...按任意键结束...

In your code sample the minimal API was taking the HTTP response you are creating as body of An HTTP response.在您的代码示例中,最小的 API 将您创建的 HTTP 响应作为 HTTP 响应的主体。 So not the right approach.所以不是正确的方法。 I used Postman to test, it made it easier to discover that.我使用 Postman 进行测试,它更容易发现。

Since you need binary or As we call it stream, Looking at MS docs for minimal API I found this: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore-6.0#stream由于您需要二进制或我们称之为流,因此查看 MS 文档以获取最小 API 我发现: https ://docs.microsoft.com/en-us/aspnet/core/fundamentals/minimal-apis?view=aspnetcore- 6.0#流

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM