ASP.NET Web API Custom JsonConverter is never called

So here is my situation. I am implementing a WEB API in a WebForms application. I have a bunch of dynamic classes, which are essentially dictionaries that a custom JSON serializer should use to work correctly (because the default converter just shows a mess of key pairs).

So, first I created a custom JSON converter:

/// <summary>
/// A class to convert entities to JSON
/// </summary>
public class EntityJsonConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsSubclassOf(typeof(Entity));
    }

    public override bool CanRead
    {
        get { return true; }
    }

    public override bool CanWrite
    {
        get { return true; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        // Details not important. This code is called and works perfectly.
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Details not important. This code is *never* called for some reason.
    }
}

Once I have this defined, I then paste it into the global JSON media type formatter:

        // Add a custom converter for Entities.
        foreach (var formatter in GlobalConfiguration.Configuration.Formatters)
        {
            var jsonFormatter = formatter as JsonMediaTypeFormatter;
            if (jsonFormatter == null)
                continue;

            jsonFormatter.SerializerSettings.Converters.Add(new EntityJsonConverter());
        }

And finally, my test API (in the future there will be many more added, I'm just trying to check the system at the moment, "Contact" inherits from "Entity"):

public class ContactController : ApiController
{
    public IEnumerable<Contact> Get()
    {
        // Details not important. Works perfectly.
    }

    [HttpPost]
    public bool Update(Contact contact)
    {
        // Details not important. Contact is always "null".
    }
}

So here is what I see when debugging:

Calling the get website:

  • Controller.Get. .
  • .CanConvert . false.
  • .CanConvert Contact. true.
  • Converter.CanWrite. true.
  • Converter.WriteJson. JSON
  • JSON .

- "":

  • .CanConvert Contact. true.
  • Controller.Update. "" "null".

. , , , , . - , ?

!

+7
1

, . .

... JSON . . ...

Nevermind!

+6

Source: https://habr.com/ru/post/1658898/


All Articles