1

I am writing a web-api in asp.net. I have following problems: I have an interface and a class implementing that interface

public interface Item
{
    string Name { get; set; }
    string Description { get; set; }
}

public class ConcreteItem : ITem
{
    public ConcreteItem()
    {
    }
    string Name { get; set; }
    string Description { get; set; }
}

In my controller class i have following method

[HttpPost]
    public IHttpActionResult ByGivenItems([FromBody] IEnumerable<Item> items)
    {
      //Do something here
    }

The problem is when i send some content to the webservice (json formatted). The array is empty if i have the signature according to below

public IHttpActionResult ByGivenItems([FromBody] IEnumerable<Item> items)

But changing to

public IHttpActionResult ByGivenItems([FromBody] IEnumerable<ConcreteItem> items)

works. What should i do to let the json converter deserialize it to correct type? I am quite new in the C# world, so i need a good explanation how to do.

I have tested it through postman by sending some data.

Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69
Mimmi
  • 11
  • 2
  • 3
    What do you *expect* it to do? It cannot create an instance of an `interface`, and you're asking it to deserialize JSON to an `IEnumerable`, when `Item` cannot be instanced, which means it would have to *guess* at what class `Item` can be instanced to, and what happens if you have two `ConcreteItem` classes that are identical? How does it choose which one to use? – Der Kommissar Feb 04 '17 at 19:56
  • 1
    Looks very similar to [NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable](http://stackoverflow.com/q/11754633/3744182). Does that answer your question? – dbc Feb 04 '17 at 20:41
  • I understand that i need to serialize to a concrete type. But my question is how do it in asp.net web-api system since the framework doe's mostly all the work. Can i say to json converter convert to a ConcreteItem but keep the signature of the method `public IHttpActionResult ByGivenItems([FromBody] IEnumerable items)` – Mimmi Feb 04 '17 at 20:56
  • The linked question shows that the `[JsonConverter]` attribute can be applied to the interface. You can also add the converter to `SerializerSettings` as shown in [this answer](https://stackoverflow.com/questions/7427909/how-to-tell-json-net-globally-to-apply-the-stringenumconverter-to-all-enums/7438186#7438186). – dbc Feb 04 '17 at 21:17
  • @Mimmi you try looking into custom model binders. Now by convention, controller actions are not suppose to be taking interfaces as parameters for the same reasons already mentioned, but you and play around with model binders and take the raw input and deserialize it yourself – Nkosi Feb 05 '17 at 02:37

0 Answers0