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