【问题标题】:WebApi Model binding w/ 2 different objects与/ 2个不同对象的Web Api模型绑定
【发布时间】:2016-04-28 11:10:36
【问题描述】:

我需要创建一个端点,但是这个端点可以有多种类型的输入,表单本身可以根据配置改变,所以我试图创建至少 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 以遵守某些规则,例如“必需”和“范围 0-X”。

我也没有什么要拥有一个具有所有属性的对象,而只满足其中的一些。

提前致谢

【问题讨论】:

    标签: asp.net web asp.net-web-api asp.net-web-api2 model-binding


    【解决方案1】:

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

    例如,在这里您可以在 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");
    }
    

    【讨论】:

      猜你喜欢
      • 2014-01-17
      • 2016-05-23
      • 1970-01-01
      • 2012-09-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多