澄清IAsyncEnumerable如何与ASP.NET Web API一起使用 [英] Clarification on how IAsyncEnumerable works with ASP.NET Web API

查看:151
本文介绍了澄清IAsyncEnumerable如何与ASP.NET Web API一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.NET Web API项目中探索IAsyncEnumerable时遇到了一个有趣的行为. 考虑以下代码示例:

I encountered an interesting behavior while exploring IAsyncEnumerable in an ASP.NET Web API project. Consider the following code samples:

    // Code Sample 1
    [HttpGet]
    public async IAsyncEnumerable<int> GetAsync()
    {
        for (int i = 0; i < 10; i++)
        {
            await Task.Delay(1000);
            yield return i;
        }
    }


    // Code Sample 2
    [HttpGet]
    public async IAsyncEnumerable<string> GetAsync()
    {
        for (int i = 0; i < 10; i++)
        {
            await Task.Delay(1000);
            yield return i.ToString();
        }
    }

样本1(int数组)返回{}作为JSON结果.

Sample 1 (int array) returns {} as JSON result.

样本2返回预期结果["0","1","2","3","4","5","6","7","8","9"].但是,等待10秒钟后立即返回整个JSON数组.当数据从IAsyncEnumerable接口获得预期的可用时,不应该返回它吗?还是应该使用此Web API的任何特定方式?

Sample 2 returns expected result ["0","1","2","3","4","5","6","7","8","9"]. However, entire JSON array is returned at once after 10 seconds of wait. Shouldn't it be returned as data becomes available as expected from IAsyncEnumerable interface? Or is there any specific way this web api should be consumed?

推荐答案

Web api调用不会每秒返回部分json.是json序列化程序,必须等待10x1秒(或调用json序列化程序的代码,这是ASP .NET的一部分).框架代码和序列化程序获得所有数据后,将对其进行序列化并作为单个响应提供给客户端.

A web api call will not return partial json every second. It's the json serialiser who has to wait 10x1second (or the code that calls the json serialiser, which is part of ASP .NET). Once the framework code and the serialiser get all data, it will be serialised and served to the client as a single response.

我们可以阅读ASP.NET Core Web API中的控制器操作返回类型:

在ASP.NET Core 3.0和更高版本中,从操作返回IAsyncEnumerable:

In ASP.NET Core 3.0 and later, returning IAsyncEnumerable from an action:

  • 不再导致同步迭代.
  • 变得与返回IEnumerable一样有效.
  • ASP.NET Core 3.0和更高版本在将以下操作的结果提供给序列化程序之前会对其进行缓冲:

    ASP.NET Core 3.0 and later buffers the result of the following action before providing it to the serializer:

    public IEnumerable<Product> GetOnSaleProducts() =>
      _context.Products.Where(p => p.IsOnSale);
    

    这篇关于澄清IAsyncEnumerable如何与ASP.NET Web API一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆