Web Api 模型与/ 2 个不同的对象绑定

WebApi Model binding w/ 2 different objects

我需要创建一个端点,但这个端点可以有多种类型的输入,表单本身可以根据配置更改,所以我试图创建至少 2 个对象作为可能的输入。

类似于:

public class ParticipationsController : ApiController
{

 public HttpResponseMessage Post([FromBody]Models.SimpleParticipationModel sModel, [FromBody]Models.CompleteParticipationModel cModel)
    {
        if (!ModelState.IsValid) // this might not be this way here 
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }

        return Request.CreateResponse(HttpStatusCode.OK, "Ok");
    }

我的观点是避免有多个端点并更改页面中的大量渲染。

我的对象包含 DataAnotations 以遵守某些规则,例如 "Required" 和 "Range 0-X"。

我也不知道有什么属性的对象,只实现了其中的一部分。

提前致谢

这可能是不可能的。为每个对象创建两个端点或创建包含上述两个对象的对象。

例如,这里您可以在API 操作中传递一个ViewModel 对象,基本上包括这两个对象。这也将维护对象属性上的数据注释行为。

public class ViewModel
{ 
     SimpleParticipationModel  sModel {get;set;}
     CompleteParticipationModel  cModel {get;set;}
}

public class ParticipationsController : ApiController
{

 public HttpResponseMessage Post([FromBody]ViewModel)
 {
    if (!ModelState.IsValid) // this might not be this way here 
    {
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }

    return Request.CreateResponse(HttpStatusCode.OK, "Ok");
}