MVC Web API Binding Model to a Derived Class

本秂侑毒 提交于 2020-01-13 14:29:02

问题


I am looking at how to bind a model to a derived class within MVC Web API, the issue I have is that I think I have found about 5 ways of doing it...

What I have is:

Models ->

  • ModelBase
  • ModelA : ModelBase
  • ModelB : ModelBase

Controller then containers the method:

Post(ModelBase model) {}

The data that is posted will be ModelA or ModelB, I want to add information to the HTTP Request metadata (think Content-Type: application/json; type=ModelA) and based on this tell MVC to bind the posted content to either A or B.

In code I imagine something like:

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

How has everyone else does this? Or how would you recommend doing this?

I've seen ParameterBinding, IModelBinder, MediaTypeFormatter, etc. MVC is great, but sometimes its hard to think which hook you should use...

EDIT:

To add more information, the ModelBase will most likely become an interface, and there will be hundreds of concrete classes.

It is going to be for CQRS: Command and then the ConcreteCommandA, ConcreteCommandB, these will get pushed off to a dispatcher, I don't want to be making an action for each command, a central action to receive these commands, deserialize them to the correct type and forward them on.

来源:https://stackoverflow.com/questions/24124176/mvc-web-api-binding-model-to-a-derived-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!