要求 C# Web API 返回文本/纯内容类型

问题描述 投票:0回答:1

使用用 C# 编写的具有最少 API 的 ASP.NET Core 6 Web API,我想返回数据流而不先将数据加载到内存中。在我的例子中,这是由 Apache Spark 编写的 JSONL(JSON 行)数据。 JSONL 是一种基于文本的格式。

下面的代码设置了

Content-Type: application/json
,这对我的用例来说是不正确的。设置此类型然后用数组包装整个内容,并在有引号的地方添加转义反斜杠字符。

它应该改为设置

Content-type: text/plain
这将保留行的原始格式,并允许此端点的消费者一次流式传输和处理一行,而无需将整个响应主体加载到客户端的内存中。

是否可以在保持流

content-type
的同时更改此
Transfer-Encoding: chunked
并且不解析或修改我从.jsonl文件读取的行内容?

app.MapGet("/stream/data", () =>
{
    async IAsyncEnumerable<string> Stream()
    {
        using (StreamReader file = new StreamReader(filePath))
        {
            while (!file.EndOfStream)
            {
                yield return await file.ReadLineAsync() ?? string.Empty;
            }
        }
    }

    return Stream();
});
c# stream asp.net-core-webapi minimal-apis jsonlines
1个回答
1
投票

您可以设置自定义

IResult
处理每行读取和写入响应的行。

public sealed class JsonLines : IResult
{
    private readonly string _filePath;

    public JsonLines(string filePath)
        => _filePath = filePath;

    public async Task ExecuteAsync(HttpContext httpContext)
    {
        httpContext.Response.ContentType = "text/plain"; // Or "application/json"

        using var reader = new StreamReader(_filePath);

        while (!reader.EndOfStream)
        {
            var line = await reader.ReadLineAsync();
            if (line is not null)
            {
                await httpContext.Response.WriteAsync(line);
            }
        }
    }
}

您的

MapGet
将如下所示。

app.MapGet("/stream/data", () => new JsonLines(@"c:\yourdatafile.json"));

Fiddler 显示预期的标头存在,并且响应被分块。


您可能会重新考虑将

Content-Type
标头(返回)设置为
application/json
,因为 ASP.NET Core 将不再涉及它。

© www.soinside.com 2019 - 2024. All rights reserved.