Web Api Model Binding and Polymorphic Inheritance

后端 未结 2 1053
余生分开走
余生分开走 2020-12-15 04:57

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         


        
相关标签:
2条回答
  • 2020-12-15 05:03

    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.

    0 讨论(0)
  • 2020-12-15 05:08

    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");
        }
    }
    

    0 讨论(0)
提交回复
热议问题