I had an REST API targeting AspNetCore 2.2 with an endpoint that allows download of some big json files. After migrating to AspNetCore 3.1 this code stopped working:
try
{
HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
HttpContext.Response.Headers.Add("Content-Type", "application/json");
using (var bufferedOutput = new BufferedStream(HttpContext.Response.Body, bufferSize: 4 * 1024 * 1024))
{
await _downloadService.Download(_applicationId, bufferedOutput);
}
}
catch (Exception ex)
{
_logger.LogError(ex, ex.Message);
}
This is the download method, that created the json that I want to return on the HttpContext.Response.Body:
public async Task Download(string applicationId, Stream output, CancellationToken cancellationToken = default(CancellationToken))
{
using (var textWriter = new StreamWriter(output, Constants.Utf8))
{
using (var jsonWriter = new JsonTextWriter(textWriter))
{
jsonWriter.Formatting = Formatting.None;
await jsonWriter.WriteStartArrayAsync(cancellationToken);
//write json...
await jsonWriter.WritePropertyNameAsync("Status", cancellationToken);
await jsonWriter.WriteValueAsync(someStatus, cancellationToken);
await jsonWriter.WriteEndArrayAsync(cancellationToken);
}
}
}
Now I get this exception: "Synchronous operations are disallowed in ASP.NET Core 3.0" How can I change this code to work without using AllowSynchronousIO = true;