Can I pass an interface based object to an MVC 4 WebApi POST?

前端 未结 4 1235
半阙折子戏
半阙折子戏 2020-12-30 03:24

I want to have an API as such:

public class RelayController : ApiController
{
    // POST api/values
    public void Post([FromBody]IDataRelayPackage package         


        
4条回答
  •  灰色年华
    2020-12-30 03:30

    Json.NET (the default Json serializer for ASP.NET Web API) can handle this situation. All you need to do is change the serializer settings, and set TypeNameHandling to All (or Objects). This will add a "$type"-json property to your json, containing the type name of your instance. On the other side it'll try to deserialize to this type again.

    We used this for ourselves, taking an abstract base class as type.

提交回复
热议问题