ASP.NET高级[FromBody]映射

时间:2018-09-14 18:59:55

标签: asp.net asp.net-web-api asp.net-core-webapi

请考虑以下模型:

public class Shape {
   public Guid Id {get;set;} 
   public string Color {get;set;}
}

public class Circle : Shape {
   public int Contour {get;set;}
}

public class Rectangle : Shape {
   public bool IsSquare {get;set;}
}

这纯粹是演示,我有一个基类,而派生类具有不同的属性。

在我的Javascript客户端中,我有一个List,形状各异。

const shapes = [
   { id: ..., color: 'red', contour: 23 },
   { id: ..., color: 'blue', isSquare: false }
];

当我将这些数据发布到服务器时,我需要知道它是Circle还是Rectangle。我的Web API中定义了以下端点。

[HttpPost("shapes")]
public IActionResult Post([FromBody] IEnumerable<Shape> shapes) 
{
   foreach(var shape in shapes) 
   {
      // how do I know if shape is of type Square/Circle?
      // and how do I cast the shape to the corresponding type?
      if (shape is Circle) 
      {
          shapeService.InsertCircle(shape as Circle);
      }
      else if (shape is Rectangle) 
      {
          shapeService.InsertRectangle(shape as Rectangle);
      }
   }
   return Ok();
}

所以问题是,一旦进入控制器功能,是否可以将形状转换为相应的类型?

0 个答案:

没有答案