Multiple Posted Types asp.net 5 MVC 6 API

孤人 提交于 2019-12-12 11:46:58

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/30833524/multiple-posted-types-asp-net-5-mvc-6-api

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