G
Gulzar Ahamed
Guest
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 version is
<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" />
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
Continue reading...
My used package version is
<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" />
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
Continue reading...