I am asking if anyone knows if it is possible to to pass into a Web Api a concrete class that inherits from a abstract class.
For example:
public ab
If one really wanted to implement what is asked in the question, there is a custom way to do it.
First, create a custom json converter that is inherited from JsonConverter
, in it pick a target class and deserialize an instance.
Then, in your WebApiConfig.Register
you add your new converter into config.Formatters.JsonFormatter.SerializerSettings.Converters
and enjoy this monstrosity in action.
Should you do it? No.
Understanding how to use such API will bring no joy to any new users, documenting this will not be easy, and most importantly - there are no benefits in implementing it this way. If input types are different, then they deserve separate API methods with different URLs. If only few properties are different - make them optional.
Why the example did not work? The TypeNameHandling is from Json.NET, Web API knows nothing about it, and type information is not part of the JSON spec, so there is no standard way to solve this particular issue.
This is possible via the default model binding. check below method.
public abstract class RequestBase
{
public int ID { get; set; }
}
public class MyRequest : RequestBase
{
public string Name { get; set; }
}
[RoutePrefix("api/home")]
public class HomeController : ApiController
{
[HttpPost]
[Route("GetName")]
public IHttpActionResult GetName([FromBody]MyRequest _request)
{
return Ok("Test");
}
}