It seems perfectly valid if we have a API controller with a method like below:
[HttpPost]
public IHttpActionResult DoStuff([FromBody]ModelA modelA, [FromBody]ModelB modelB)
Note the two [FromBody]
attribute.
The question is, how to call such a method ?
localhost/test/DoStuff/
POST Data:
<?xml version="1.0"?>
<ModelA>
...
</ModelA>
<ModelB>
...
</ModelB>
does not seem to be recognized. Any ideas why ?
EDIT: The error data is like below:
<?xml version="1.0"?>
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>Can't bind multiple parameters ('model1' and 'model2') to the request's content.
</ExceptionMessage>
</Error>
I would say that instead of justifying this lack of support of multiple models with documentation, you should find an argument in terms of software architecture perspective: ASP.NET Web API is built on top of MVC paradigm, where a view is bound to a model and handled by a controller.
In other words: 1 Model, 1 View, 1 Controller.
Your use case shouldn't be solved with 2 models, but using a DTO. Instead of binding 2 parameter to 2 models, design a DTO which includes both models as associations of the whole DTO:
// You don't need [FromBody] since complex types are already taken
// from the request body
public IHttpActionResult DoStuff(SomeDto dto)
Create a ViewModel which consists of two models and use it as a single Model in your controller.
public class MergedModel
{
public ModelA A{get; set;}
public ModelB B{get; set;}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With