ASP.NET Advanced [FromBody] mapping

Viewed 76

Consider the following Models:

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;}
}

This is pure as demonstration, I have a base class with derived classes with different properties.

In my Javascript client I have a List with different shapes.

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

When I post this data to the server, I need to know whether it's a Circle or a Rectangle. I have the following Endpoint defined in my 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();
}

So the question is, is it possible to cast shapes to their corresponding types once I'm inside the controller function?

0 Answers
Related