Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Posted Types asp.net 5 MVC 6 API

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?

like image 724
TheBreadman Avatar asked Dec 20 '22 03:12

TheBreadman


2 Answers

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.

like image 93
Brian Mains Avatar answered Dec 22 '22 01:12

Brian Mains


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.

like image 30
McGuireV10 Avatar answered Dec 21 '22 23:12

McGuireV10