Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Text.Json in Azure Function v3: JsonResult.SerializerSettings must be an instance of type JsonSerializerSettings

I have a set of Azure Functions v3 running on .NET Core 3.1.

I need to specify custom System.Text.Json converters so I provided a custom JsonSerializerOptions instance when I build a JsonResult in my function:

return new JsonResult(<ContractClass>, NSJsonSerializerOptions.Default)
{
    StatusCode = StatusCodes.Status200OK
};

Question

I get the following error and I am not sure where Newtonsoft is coming from since ASP.NET Core is supposed to use System.Text.Json:

Microsoft.AspNetCore.Mvc.NewtonsoftJson: Property 'JsonResult.SerializerSettings' must be an instance of type 'Newtonsoft.Json.JsonSerializerSettings'.

Update

I found out that the JsonResult instance is looking for an implementation of IActionResultExecutor<JsonResult> and gets an NewtonsoftJsonresultExecutor instead of an SystemTextJsonResultExecutor. Here is the code for the JsonResult's ExecuteResultAsync method:

JsonResult

I would have though that the Azure Function would rely on ASP.Net Core which relies on System.Text.Json.

like image 368
Kzrystof Avatar asked Nov 25 '22 23:11

Kzrystof


1 Answers

As a workaround, I just created a new class which inherits from ContentResult.

using System.Text.Json;
using Microsoft.AspNetCore.Mvc;

namespace BlazorApp.Api.Models
{
    public class SystemTextJsonResult : ContentResult
    {
        private const string ContentTypeApplicationJson = "application/json";

        public SystemTextJsonResult(object value, JsonSerializerOptions options = null)
        {
            ContentType = ContentTypeApplicationJson;
            Content = options == null ? JsonSerializer.Serialize(value) : JsonSerializer.Serialize(value, options);
        }
    }
}

And this is used like:

[FunctionName("IntakeCount")]
public async Task<IActionResult> GetIntakeCountAsync([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req)
{
    var result = await _httpClient.GetFromJsonAsync<...>(...);

    return new SystemTextJsonResult(result);
}
like image 93
Stef Heyenrath Avatar answered Dec 10 '22 20:12

Stef Heyenrath