A. Non
A. Non

Reputation: 179

How do I implement Post([FromBody] IMessage msg) in my .Net Core 2.1 web api Controller?

I get the following exception when I send a simple JSON structure implementing the interface IMessage:

Could not create an instance of type TestService2.IMessage. Type is an interface or abstract class and cannot be instantiated. Path 'Id', line 2, position 7.

Upvotes: 1

Views: 1715

Answers (1)

A. Non
A. Non

Reputation: 179

I absolutely agree that using classes is the way to go!

If, however, for some obscure/Stupid reason, you have to use interfaces like me, there is a simple way of mapping it to a class with JSON.

In the Startup Method, define the Contracts for the interface:

services.AddMvc()
           .AddJsonOptions(o => { o.SerializerSettings.ContractResolver.ResolveContract(typeof(IMessage)).Converter = new MyJsonConverter<IMessage, Message>();})

Where IMessage is said interface, and MyJsonConverter is derived from JsonConverter, for example:

public class MyJsonConverter<Tin, Tout> : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        //Your logic here
        return (objectType == typeof(Tin) );
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        //deserializing from the implementation Class
        return serializer.Deserialize<Tout>(reader);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        //use standard serialization
        serializer.Serialize(writer, value);
    }
}

Upvotes: 3

Related Questions