azure-functions-openapi-extension icon indicating copy to clipboard operation
azure-functions-openapi-extension copied to clipboard

Synchronous operations are disallowed

Open throwaway34059 opened this issue 11 months ago • 1 comments

Describe the issue .net 8 Azure Function in program.cs when configuring .ConfigureFunctionsWebApplication(worker => worker.UseNewtonSoftJson()) I will get a an error "Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead"

That led me to this link.

The code:

public async Task<HttpResponseData> Get([HttpTrigger(AuthorizationLevel.Function, "get", Route = "v1/user")] HttpRequestData req)
{
...
 var response = req.CreateResponse(HttpStatusCode.OK);          
 await response.WriteAsJsonAsync(user);
 return response;

}

It will bomb out on .WriteAsJsonAsync() from swagger and postman. It could be my object I am returning but..

My work around:

My work around was to remove worker => worker.UseNewtonSoftJson() from my config.

var host = new HostBuilder()
    .ConfigureFunctionsWebApplication() //Note: OpenApi says to configure this as worker => worker.UseNewtonSoftJson(). This will cause a Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead. I removed it and things seem to work? 
    .ConfigureServices((hostContext, services) =>
...

This works for swagger and json. It could be the object I am serializing that doesn't play nice with NewtonSoft. idk. The link make it seem like there's some other issue with flushing on write.¯_(ツ)_/¯.

throwaway34059 avatar Mar 04 '24 15:03 throwaway34059

Same here. Instead I use WriteAsync and Stream. Works...

//await response.WriteAsJsonAsync(responseDTO); <-- dont work
var serialized = JsonConvert.SerializeObject(responseDTO);
var ms = new MemoryStream(Encoding.UTF8.GetBytes(serialized));
await response.Body.WriteAsync(ms.ToArray());

mvinicius2k avatar Apr 18 '24 20:04 mvinicius2k