I have this formatter in my .NET Core 3.1
project (which I recently upgraded from 2.1
):
public class JilOutputFormatter : TextOutputFormatter {
public JilOutputFormatter() =>
JilFormatterConfig.AddSupportedHeaders(SupportedMediaTypes, SupportedEncodings);
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding) {
using (var writer = new StreamWriter(context.HttpContext.Response.Body)) {
JSON.Serialize(context.Object, writer, MyOptions);
writer.Flush();
}
return Task.FromResult(true);
}
}
And I'm adding it to pipeline with this snippet:
services.AddMvcCore(o => {
o.OutputFormatters.Insert(0, new JilOutputFormatter());
}).AddOthersBlahBlah();
It was working like a charm when the application was on 2.1
. But now on 3.1
I'm getting this error:
An unhandled exception occurred while processing the request. InvalidOperationException: Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead.
I tried to async the write operation, but can't find the method on Jil
. Do you have any idea please?
NOTE: I know there are some answers - like this one - that are saying how to AllowSynchronousIO
. But I'm interested on how to async write in Jil
.
You'll have to use the 3.0 alpha versions. Jil doesn't even include the word
Task
in the source code in the latest stable version, 2.17 (or Github search is having some issues).Version 3.0 uses Pipelines directly. You can use the SerializeAsync(T, PipeWriter , Encoding, Options, CancellationToken). Maybe you can work with HttpContext.Response.BodyWriter. I haven't tested this though.
Eg :