MVC Web API绑定模型到派生类
我正在研究如何将模型绑定到MVC Web API中的派生类,我的问题是我认为我已经找到了5种方法…
我所拥有的是:
型号 – >
- 模型库
- ModelA:ModelBase
- ModelB:ModelBase
控制器然后容器方法:
Post(ModelBase model) {}
发布的数据将是ModelA或ModelB,我想向HTTP Request元数据添加信息(想想Content-Type:application / json; type = ModelA)并基于此告诉MVC将发布的内容绑定到A或B.
在代码中,我想象的是:
Bind(request, bindingContext) { // check request headers and then... bindingContext.ModelType=typeof(ModelA); // let the framework continue doing its thing deserializing the content base.Bind(request, bindingContext); }
其他人怎么做到这一点? 或者你会如何推荐这样做?
我见过ParameterBinding,IModelBinder,MediaTypeFormatter等.MVC很棒,但有时很难想到你应该使用哪个钩子……
编辑:
要添加更多信息,ModelBase很可能成为一个接口,并且将有数百个具体类。
它将用于CQRS:Command,然后是ConcreteCommandA,ConcreteCommandB,这些将被推送到调度程序,我不想为每个命令做一个动作,一个接收这些命令的中心动作,将它们反序列化为正确的类型并转发它们。