0

I'm using AspNet Core 3.1. I implemented a custom Json converter for NewtonSoft Json as below:

public class CustomConverter : Newtonsoft.Json.JsonConverter
{
    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsAssignableFrom(typeof(Device));
    }
}

And registered in DI like so

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers(o => { o.ModelBinderProviders.Insert(0, new DeviceModelBinderProvider()); })
        .AddNewtonsoftJson(o => o.SerializerSettings.Converters.Insert(0, new CustomConverter()));
}

And my controller looks like:

[ApiController]
[Route("test")]
public class TestController : ControllerBase
{
    [HttpPost]
    public IActionResult Test([FromBody]Device dto)
    {
        if (dto == null)
        {
            return this.Problem();
        }

        return Ok();
    }
}

However, when deserializing the DTO, this formatter is not getting called. It does get called when serialising the response. My request from Postman looks like

curl --location --request POST 'http://localhost:5000/test' \
--header 'Content-Type: application/json' \
--data-raw '{
    "ScreenSize": "1",
    "Kind": "SmartPhone"
}'
dbc
  • 104,963
  • 20
  • 228
  • 340
kovac
  • 4,945
  • 9
  • 47
  • 90
  • 1
    No, I'm not using controller name in the route. Routing is working and my controller action gets the request. The `dto` just ends up being `null`. – kovac May 19 '20 at 02:27
  • 1
    You throw new NotImplementedException() in your JsonConverter.It would get Http status 500 error.What is your DeviceModelBinderProvider? – Rena May 19 '20 at 04:28
  • @Rena Actually, I didn't let it throw. I put a break point in all those methods to see if ithey gets called and they don't. – kovac May 19 '20 at 06:08
  • 1) It should be [`typeof(Device).IsAssignableFrom(objectType)`](https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonConverter.cs#L146). 2) How do you know the CustomConverter is not getting invoked? Maybe the exception is getting swallowed somewhere? – dbc May 28 '22 at 19:53

0 Answers0