1

I have a asp.net application that uses

builder.Services.AddControllers()
    .AddNewtonsoftJson();

This causes the return of the controller not to run asynchronous

        [HttpGet("IAsyncTest")]
        public IAsyncEnumerable<TestDTO> GetTestValue()
        {
            return _getValues();
        }

        private static readonly TestDTO[] _values = new[]
        {
            new TestDTO {IntValue= 1, StringValue = "Value 1"},
            new TestDTO {IntValue= 2, StringValue = "Value 2"},
            new TestDTO {IntValue= 3, StringValue = "Value 3"},
            new TestDTO {IntValue= 4, StringValue = "Value 4"},
            new TestDTO {IntValue= 5, StringValue = "Value 5"},
        };

        private async IAsyncEnumerable<TestDTO> _getValues()
        {
            foreach (var value in _values)
            {
                yield return value;
                await Task.Delay(TimeSpan.FromSeconds(20));
            }
        }

Is there a way to use Newtonsoft only in certain controllers not all of them? Or specify which controller uses Text.Json.

Or Is it possible to create a custom formatter that uses that Text.Json for IAsyncEnumerable.

Code example is here: GitHub Link

Thanks for helping

  • Newtonsoft doesn't have anything to do with sync or async is your controller, as well as Text.Json. Can you tell what is your problem? Do you want to use sync or async, or you want to use a special serializer? – Serge Dec 14 '22 at 00:24
  • 2
    @Serge - OP wants to use async, but is currently using Newtonsoft, which doesn't support async. System.Text.Json does support async and will in fact serialize an `IAsyncEnumerable` asynchronously, when serialized via `JsonSerializer.SerializeAsync()`. See [System.Text.Json IAsyncEnumerable serialization](https://learn.microsoft.com/en-us/dotnet/core/compatibility/serialization/6.0/iasyncenumerable-serialization), so OP is looking for a way to use System.Text.Json for `IAsyncEnumerable` while sticking with Newtonsoft for everything else. – dbc Dec 14 '22 at 01:27
  • @dbc I don't belive that it is one such a big json object that needs to be serialized async. Certainly OP has a collection that needs to be serialized, so it is quite easily can be created a code that will serialize each json object sync using newtonsoft but, but add a string to collection using async. – Serge Dec 14 '22 at 01:33
  • @Serge - thats could work. @oussamabenyaala, could you clarify how many items you need to serialize? Could you build a `List` asynchronously, but serialize it synchronously as Serge suggests? – dbc Dec 14 '22 at 01:43
  • From the link provided by dbc, `System.Text.Json` now supports serializing and deserializing of `IAsyncEnumerable` instances. But Do you want to use System.Text.Json only when return type is IAsyncEnumerable? – Xinran Shen Dec 14 '22 at 08:24

0 Answers0