简体   繁体   中英

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM