I can use [FromBody] for single type , but is there any way to use multiple?
From the searching and reading I've done there is not a way, but i don't know if a way has been added in MVC 6.
If not, where would be best to start with custom way.
What should i be researching and looking for best method or place to hook in just before model binding so i can include my own method?
The best way is to create a composite wrapper:
public class Wrapper
{
public ModelA A { get; set; }
public ModelB B { get; set; }
}
Put Wrapper in the parameter list and mark that [FromBody]
. You can't use that attribute more than once because all of the contents of the body are assumed to match the parameter type.
The composite wrapper approach is great if you can easily share your model between the caller and server, but a more generic approach is to use JObject:
using Newtonsoft.Json.Linq; // this gets you to JObject
[Route("svc/[controller]/[action]")]
public class AccountController : Controller
{
[HttpPost("{accountid}")]
public IActionResult UpdateAccount(int accountid, [FromBody]JObject payload)
{
var loginToken = payload["logintoken"].ToObject<LoginToken>();
var newAccount = payload["account"].ToObject<Account>();
// perform update
return this.Ok("success");
}
}
You could probably also go with a Tuple
which would give you the concrete types specified in the parameter list. This would be great if your clients were always .NET apps (.NET 4.0 or later, specifically) but you'd probably want to write a helper library to get the right wire format if you were trying to come from AJAX or something similar.
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