多态性的Web API:单个端点可能吗? [英] Polymorphism in Web API: Single endpoint possible?

查看:145
本文介绍了多态性的Web API:单个端点可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到Web API是REST专注,但我还是想配置,可以处理的命令/响应方案单个控制器的方法。到目前为止,我还没有成功...有没有办法有一个单一的API端点公认下面的类结构呢?

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 successful... is there a way to have the following class structure recognized by a single API endpoint?

[Serializable]
public abstract class Command{
    public int CommandId{get; set;}
}
[Serializable]
public class RegisterNewPersonCommand:Command{
   public string Name{get; set;}
}
//etc... various Command subclasses. Similar thing for Responses.

//now have a single endpoint to Handle Commands
public class CommandsController : ApiController{
   public Response HandleCommand(Command command){
      //handle Command based on which subclass it is
      //return appropriate Response subclass
   }
}

到目前为止似乎没有序列化系统可以处理这种情况,但我希望有人在那里发现了一个办法做到这一点:)

Thus far it doesn't seem the serialization system can handle this scenario, but I hope someone out there has found a way to do it :)

推荐答案

为了多态性的Web API工作,你将需要启用类型名处理和数据必须包含的类型信息。

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.

您需要在 WebApiConfig.cs 在方案中打开 TypeNameHandling 如果你使用JSON

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;

然后,您要发送到你的 HandleCommand(...)行动内容含有人体必须的类型信息:

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

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

有关XML,你需要使用DataContract的KnownType ...

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

顺便说一句,有没有什么具体原因正在使用 [Serializable接口] (因为POCO类型和 [DataContract] 类型也支持)?

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

这篇关于多态性的Web API:单个端点可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆