Polymorphism in Web API: Single endpoint possible?

前端 未结 1 1106
北海茫月
北海茫月 2021-02-04 09:00

I realize that the Web API is REST focused, but I would still like to configure a single controller method that can handle a Command/Response scenario. So far I haven\'t been s

相关标签:
1条回答
  • 2021-02-04 09:05

    In order for polymorphism to work in Web API, you will need to enable type name handling and the data has to contain the type information.

    You'll need to turn on TypeNameHandling in WebApiConfig.cs if you're using JSON in your scenario:

    config.Formatters.JsonFormatter.SerializerSettings.TypeNameHandling = 
        Newtonsoft.Json.TypeNameHandling.All;
    

    Then, the content body that you are sending to your HandleCommand(...) action must contain the type information:

    {"$type":"MvcApplication.Models.RegisterNewPersonCommand, MvcApplication", ... }
    

    For XML, you'll need to use DataContract's KnownType...

    By the way, is there any specific reason why you are using [Serializable] (since POCO types and [DataContract] types are also supported...)?

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