Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST in ASP.NET Web API with model property as interface

Suppose I have a model:

public class Menu
{
    public string Name { get; set; }
    public IMenuCommand Next { get; set; }
}

IMenuCommand could have different implementations, like:

public class NextStepCommand : IMenuCommand
{
    public int Step { get; set; }
}

public class VoiceCommand : IMenuCommand
{
    public string Message { get; set; }
}

And I want to POST menus with different commands to the ASP.NET Web API service. How can I do that?

The request below will create an object with specified Name, but Next command will be null:

POST http://localhost/api/menus: {"name":"bob","next":{"step":1}}
Returns 201: {"Name":"bob","Next":null}

Default Web API binders can't map my request params to the needed C# type - of course it's a tricky part. Can I use some "known-type" attribute for interface-based properties or is there any other approach to handle this case, probably a custom model binder?

like image 695
whyleee Avatar asked Dec 19 '12 01:12

whyleee


1 Answers

I think what you're looking for is Json.NET's support for type name handling. It allows you to specify the type to deserialize into by adding the "$type" json tag. You can try this code out to see how it works:

Console.WriteLine(JsonConvert.DeserializeObject<Menu>(
    @"{
         ""name"":""bob"",
         ""next"":
         {
           ""$type"" : ""ConsoleApplication.NextStepCommand,ConsoleApplication"",
           ""step"" : 1
         }
    }",
    new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Auto }).Next);

You'll have to replace the namespace and assembly name with your own, but you should see the NextStepCommand being correctly deserialized.

In WebAPI, you'll need to tweak your request to add the "$type" type information, and you'll need to enable TypeNameHandling like this:

config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;
like image 162
Youssef Moussaoui Avatar answered Oct 20 '22 00:10

Youssef Moussaoui