2016-04-28 37 views
2

我需要創建一個終點,但是這個終點可以有多種類型的輸入,表單本身可以根據配置進行更改,所以我試圖創建至少2個對象投入。WebApi模型綁定w/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"); 
    } 

我的觀點是,以避免多個終端和改變了很多renderization的頁面。

我的對象包含符合某些規則的DataAnotations,如「Required」和「Range 0-X」。

我也沒有什麼有一個對象的所有屬性,只履行其中的一些。

在此先感謝

回答

1

這可能是不可能的。可以爲每個對象創建兩個端點,也可以爲包含上述兩個對象的創建對象創建兩個端點。

例如,在這裏您可以傳遞ViewModel的一個對象在基本上包含這兩個對象的API操作中。這也將保持您的數據註解行爲在對象屬性上。

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"); 
} 
相關問題