Azure / Azure/azure-functions-dotnet-worker

Modifying serializer causes hang

Open
#2,583 1 comment 0 reactions 1 assignee Claimed by @soninaren View on GitHub
Needs: Triage (Functions)
Dominant language
C#
Stars
466
Forks
215
Avg merge
3d 10h
Merged PRs (30d)
7

Description

Originally posted by @Tri125 in https://github.com/Azure/azure-functions-dotnet-worker/issues/2131#issuecomment-2138121780

I've noticed that modifying the serializer used by the worker will cause ``HttpResponseData.WriteAsJsonAsync`` to throw ``System.InvalidOperationException: 'Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead.'`` and it will hang, leaving the client waiting for a response.

```
// program.cs

using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using Azure.Core.Serialization;

var host = new HostBuilder()
.ConfigureFunctionsWebApplication((IFunctionsWorkerApplicationBuilder builder) =>
{
builder.Services.Configure(workerOptions =>
{
// Newtonsoft configuration.
// By default System.Text.Json is used.
var settings = NewtonsoftJsonObjectSerializer.CreateJsonSerializerSettings();
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
settings.NullValueHandling = NullValueHandling.Ignore;

workerOptions.Serializer = new NewtonsoftJsonObjectSerializer(settings);
});
})
.ConfigureServices((hostBuilderContext, services) =>
{
services.AddApplicationInsightsTelemetryWorkerService();
services.ConfigureFunctionsApplicationInsights();
})
.Build();

host.Run();

```

```
// Function1.cs

using Microsoft.AspNetCore.Http;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using FromBodyAttribute = Microsoft.Azure.Functions.Worker.Http.FromBodyAttribute;

namespace FunctionApp
{
public class Dto
{
public string Name { get; set; }
}

public class Function1
{
[Function("Function1")]
public async Task Run([HttpTrigger(AuthorizationLevel.Anonymous, "post")] [FromBody] Dto input, HttpRequestData req)
{
var res = req.CreateResponse();

// This will throw System.InvalidOperationException
await res.WriteAsJsonAsync(new Dto
{
Name = "Test"
});

return res;
}
}
}

```

If I don't customize the serializer used by the worker inside `` .ConfigureFunctionsWebApplication()``, then there's no issue when using ``WriteAsJsonAsync()``

_Originally posted by @Tri125 in https://github.com/Azure/azure-functions-dotnet-worker/issues/2131#issuecomment-2138121780_

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.