neuecc / Utf8Json

Definitely Fastest and Zero Allocation JSON Serializer for C#(NET, .NET Core, Unity, Xamarin).
MIT License
2.35k stars 266 forks source link

Error with ASP.NET Core 3.1 #186

Open ramon-garcia opened 4 years ago

ramon-garcia commented 4 years ago

When attempting to use Utf8Json formatter with ASP.NET Core 3, the following error appears:

System.InvalidOperationException: Synchronous operations are disallowed. Call ReadAsync or set AllowSynchronousIO to true instead. at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpRequestStream.Read(Byte[] buffer, Int32 offset, Int32 count) at Utf8Json.JsonSerializer.FillFromStream(Stream input, Byte[]& buffer) at Utf8Json.JsonSerializer.Deserialize[T](Stream stream, IJsonFormatterResolver resolver) at Utf8Json.JsonSerializer.NonGeneric.Deserialize(Type type, Stream stream, IJsonFormatterResolver resolver) at Utf8Json.AspNetCoreMvcFormatter.JsonInputFormatter.ReadAsync(InputFormatterContext context) at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext bindingContext) at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value) at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<g__Bind|0>d.MoveNext()

ramon-garcia commented 4 years ago

I managed to get it working with the code from https://michaelscodingspot.com/the-battle-of-c-to-json-serializers-in-net-core-3/ classes Utf8JsonInputFormatter and Utf8JsonOutputFormatter.

bernardbr commented 4 years ago

I'm got the same problem. Microsoft disabled by default the synchronous i/o and announced this change here.

I'm planing to migrate to System.Text, but you can use this workaround instead:

        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<KestrelServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // If using IIS:
            services.Configure<IISServerOptions>(options =>
            {
                options.AllowSynchronousIO = true;
            });

            // Other services.
        }
faustodavid commented 4 years ago

I think it is better if you don't allow synchronous IO, because it can impact your performance.

You can implement the solution from this PR or the solution from @ramon-garcia which is the kind the same. https://github.com/neuecc/Utf8Json/pull/193/files

Just copy the file to your solution, or some common library and inject this formatter.