From 2be8a8b2a8bd056bfc024c76fb0bbedd06586950 Mon Sep 17 00:00:00 2001 From: Archi Date: Fri, 30 Jul 2021 20:54:52 +0200 Subject: [PATCH] Avoid a potential synchronous flush when serializing api authentication middleware response Might result in something along: 2021-07-30 16:39:43|ArchiSteamFarm-6766|ERROR|Microsoft.AspNetCore.Server.Kestrel|Connection id "0HMAJF2E5IVHB", Request id "0HMAJF2E5IVHB:00000005": An unhandled exception was thrown by the application. System.InvalidOperationException: Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead. at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpResponseStream.Flush() at Microsoft.AspNetCore.ResponseCaching.ResponseCachingStream.Flush() at Microsoft.AspNetCore.ResponseCompression.ResponseCompressionBody.Flush() at System.IO.StreamWriter.Flush(Boolean flushStream, Boolean flushEncoder) at System.IO.StreamWriter.Dispose(Boolean disposing) at System.IO.StreamWriter.Close() at Newtonsoft.Json.JsonTextWriter.CloseBufferAndWriter() at Newtonsoft.Json.JsonTextWriter.Close() at Newtonsoft.Json.JsonWriter.Dispose(Boolean disposing) at Newtonsoft.Json.JsonWriter.System.IDisposable.Dispose() at ArchiSteamFarm.IPC.WebUtilities.WriteJsonAsync[TValue](HttpResponse response, TValue value, JsonSerializerSettings jsonSerializerSettings) at ArchiSteamFarm.IPC.WebUtilities.WriteJsonAsync[TValue](HttpResponse response, TValue value, JsonSerializerSettings jsonSerializerSettings) at ArchiSteamFarm.IPC.Integration.ApiAuthenticationMiddleware.InvokeAsync(HttpContext context, IOptions`1 jsonOptions) at Microsoft.AspNetCore.ResponseCompression.ResponseCompressionMiddleware.Invoke(HttpContext context) at Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware.Invoke(HttpContext httpContext) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application) --- ArchiSteamFarm/IPC/WebUtilities.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/ArchiSteamFarm/IPC/WebUtilities.cs b/ArchiSteamFarm/IPC/WebUtilities.cs index cb5e29373..4de56e6b6 100644 --- a/ArchiSteamFarm/IPC/WebUtilities.cs +++ b/ArchiSteamFarm/IPC/WebUtilities.cs @@ -66,18 +66,18 @@ namespace ArchiSteamFarm.IPC { throw new ArgumentNullException(nameof(response)); } + JsonSerializer serializer = JsonSerializer.CreateDefault(jsonSerializerSettings); + response.ContentType = "application/json; charset=utf-8"; StreamWriter streamWriter = new(response.Body, Encoding.UTF8); await using (streamWriter.ConfigureAwait(false)) { - using JsonTextWriter jsonWriter = new(streamWriter); - - JsonSerializer serializer = JsonSerializer.CreateDefault(jsonSerializerSettings); + using JsonTextWriter jsonWriter = new(streamWriter) { + CloseOutput = false + }; serializer.Serialize(jsonWriter, value); - - await jsonWriter.FlushAsync().ConfigureAwait(false); } } }