none
NewtonSoft JSON SerializerSettings issue when migrated the web api service from .net core 2.2 to 3.1 RRS feed

  • Question

  • My asp.net core 3.1 webapi Service application that recently migrated from .net core 2.2 to 3.1 experience MethodNotFound exceptions due to NewtonSoft JSON assembly, it was worked fine in .net core 2.2. I want to know How to set json serializer settings in asp.net core 3.1?

    My used package versions are:- 

    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.1" />
    <!--<PackageReference Include="Microsoft.AspNetCore.Mvc.Formatters.Json" Version="2.1.1" />-->
    <PackageReference Include="WebApi.Hal" Version="3.1.0" />

    <PackageReference Include="Unity.Configuration" Version="5.11.1" />
    <PackageReference Include="Unity.Microsoft.DependencyInjection" Version="5.11.5" />   

    <PackageReference Include="Microsoft.AspNetCore.Mvc.Core" Version="2.2.5" />
    <!--<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />-->

    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="2.1.1" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.0">
    <PackageReference Include="Microsoft.Extensions.Logging.Log4Net.AspNetCore" Version="3.0.3" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.2.0" />
    <PackageReference Include="Microsoft.Extensions.Http" Version="2.1.1" />
    <PackageReference Include="log4net" Version="2.0.8" />

    <PackageReference Include="System.Security.Cryptography.ProtectedData" Version="4.5.0" />
    <PackageReference Include="System.Configuration.ConfigurationManager" Version="4.5.0" />
    <PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.2.4" />
    <PackageReference Include="log4net" Version="2.0.8" />

    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.2.0">
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.ApiExplorer" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
    <PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="3.1.1" />
    <PackageReference Include="Microsoft.Extensions.Http.Polly" Version="2.1.1" />
    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL.Design" Version="1.1.0" />

    I have given the exception below:-

    Moreover I have tried some ways in the public void ConfigureServices(IServiceCollection services) by adding AddMvc().AddJsonOptions() but nothing could yield the result except 3rd and 4th options that i have given below, but it was bit different.

    before in .net core 2.2 the response is:-

    {
      "_links": {
        "self": {
          "href": "/api/customers"
        }
      }
    }

    after migrate the response was:-
    {
        "ResourceList": null,
        "_links": [
            {
                "Curie": null,
                "Rel": "self",
                "Href": "/api/customers",
                "Title": null,
                "Type": null,
                "Deprecation": null,
                "Name": null,
                "Profile": null,
                "HrefLang": null,
                "IsTemplated": false
            }
        ],
        "_embedded": null
    }

    //first way, throws exception services.AddControllers(options => { options.OutputFormatters.RemoveType<StringOutputFormatter>(); options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>(); }); //second way, throws exception services.AddControllers(). AddJsonOptions(options => //{ options.JsonSerializerOptions.PropertyNameCaseInsensitive = true; options.JsonSerializerOptions.PropertyNamingPolicy = null; }); //third way, no exception but result bit different, which mentioned above services.AddControllers().AddNewtonsoftJson(options => { new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() }; });

    //fourt way, no exception but result bit different, which mentioned above

    services.AddControllers().AddNewtonsoftJson(options =>
    {
            options.SerializerSettings.Converters.Add(new StringEnumConverter());
            options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
     });


    using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Net; using System.Threading.Tasks; using WebApi.Hal.JsonConverters; public class HalJsonResult : JsonResult { private static readonly LinksConverter _linksConverter = new LinksConverter(); private static readonly ResourceConverter _resourceConverter = new ResourceConverter(new JsonSerializerSettings()); private static readonly EmbeddedResourceConverter _embeddedResourceConverter = new EmbeddedResourceConverter(); public HalJsonResult(HttpStatusCode statusCode, object value) : base(value) { var camelCaseResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() }; var serializerSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, ContractResolver = camelCaseResolver }; ConfigureSerializer(serializerSettings); StatusCode = (int)statusCode; } public Uri LocationHeader { get; set; } private void ConfigureSerializer(JsonSerializerSettings serializerSettings) { serializerSettings.Converters.Add(_linksConverter); serializerSettings.Converters.Add(_resourceConverter); serializerSettings.Converters.Add(_embeddedResourceConverter); serializerSettings.NullValueHandling = NullValueHandling.Ignore; SerializerSettings = serializerSettings;//This line throws exception } public override Task ExecuteResultAsync(ActionContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var services = context.HttpContext.RequestServices; var executor = services.GetRequiredService<IActionResultExecutor<JsonResult>>(); return executor.ExecuteAsync(context, this); } }

    //my controller class returns as

    var response = new HalJsonResult(HttpStatusCode.OK, itemsRepresentation);
        return response;

    Exception:-

    "System.MissingMethodException: Method not found: 'Void Microsoft.AspNetCore.Mvc.JsonResult.set_SerializerSettings(Newtonsoft.Json.JsonSerializerSettings)'.
       at NativeApp.Customers.Base.Infrastructure.HalJsonResult.ConfigureSerializer()
       at NativeApp.Customers.Base.Infrastructure.HalJsonResult..ctor(HttpStatusCode statusCode, Object value) in D:\Projects\Project10\customer-management\projects\backend\src\NativeApp.Customers.Base\Infrastructure\HalJsonResult.cs:line 25
       at NativeApp.Customer.Service.Customers.CustomerController.GetAll() in D:\Projects\Project10\customer-management\projects\backend\src\NativeApp.Customers.Service\Customers\CustomerController.cs:line 91
       at lambda_method(Closure , Object )
       at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
       at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
       at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
       at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
       at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
       at NativeApp.Customers.Base.Infrastructure.HttpExceptionMiddleware.Invoke(HttpContext context) in D:\Projects\Project10\customer-management\projects\backend\src\NativeApp.Customers.Base\Infrastructure\HttpExceptionMiddleware.cs:line 29
       at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

    ---

    with regards,

    ah






    Saturday, February 8, 2020 2:04 AM

Answers

  • ASP.NET WebAPI has a forum in  ASP.NET forums, and there is a Core forum there too.

    http://forums.asp.net/

    • Marked as answer by Gulzar Ahamed Sunday, February 9, 2020 1:06 AM
    Saturday, February 8, 2020 7:15 AM