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

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


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;