【问题标题】:How to return stream of data from Azure Function (HTTP)如何从 Azure Function (HTTP) 返回数据流
【发布时间】:2021-04-28 14:00:55
【问题描述】:

我需要从 Azure 函数进行一系列数据库调用,并在结果可用时将结果(文本块)返回给 http 调用者。这可能在一分钟左右的过程中偶尔发生。

我不想要“文件下载”响应,只是通过响应流发送的数据。

有没有办法在 Azure 函数中写入响应正文流?

编辑:

尝试创建我自己的 IActionResult 在写入响应正文流Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead.时遇到问题

【问题讨论】:

  • 您可以创建自己的IActionResult 实现,以更好地控制底层响应流。
  • @Oliver 我确实尝试过,但遇到了Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead 的各种问题。

标签: c# azure function .net-core


【解决方案1】:

这是一个HttpTrigger Azure 函数的示例:

[FunctionName("Function1")]
public async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
    ILogger log)
{
    return new OkResult();
}

您可以使用HttpRequest req 参数获取响应对象:

var response = req.HttpContext.Response;

我们可以去掉返回类型,直接返回Task,然后像这样流式传输数据:

public class Function1
{
    private async IAsyncEnumerable<string> GetDataAsync()
    {
        for (var i = 0; i < 100; ++i)
        {
            yield return "{\"hello\":\"world\"}";
        }
    }

    [FunctionName("Function1")]
    public async Task Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        var response = req.HttpContext.Response;

        response.StatusCode = 200;
        response.ContentType = "application/json-data-stream";

        await using var sw = new StreamWriter(response.Body);
        await foreach (var msg in GetDataAsync())
        {
            await sw.WriteLineAsync(msg);
        }

        await sw.FlushAsync();
    }
}

【讨论】:

  • 非常好。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-25
  • 2018-09-30
  • 2021-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多