Q:

WebApi2 FromBody RequestMessage of different types

I'm designing an ASP.Net Webapi 2 solution which can possibly receive one of the forms of a request message from the [Frombody] as below. 
How should I design the concrete class that will bind to the incoming request message? Any suggestion would be much appreciated.
<?xml version="1.0" encoding="utf-8"?>
<RequestMessage>
  <Shapes>
    <RectangleInfo></RectangleInfo>
  </Shapes>
</RequestMessage>

or

<RequestMessage>
  <Shapes>
    <CicleInfo></CicleInfo>
  </Shapes>
</RequestMessage>

or

<RequestMessage>
  <Shapes>
    <SquareInfo></SquareInfo>
  </Shapes>
</RequestMessage>

A:

Consider using the ModelBinder interface and return an IShape of the correct type: RectangleShape, CicleShape or SquareShape.  Your controller method will look something like this when you get done:
    public Task<HttpResponseMessage> GetShape(
        [ModelBinder] IShape shape = null) { ... }

Your binder will look something like
using System;
using System.Net;
using System.Web.Http.Controllers;
using System.Web.Http.ModelBinding;

/// <summary>Web API ModelBinder for Shape.</summary>
/// <example>
/// At service startup include:
/// config.Services.Insert(typeof(ModelBinderProvider), 0, new SimpleModelBinderProvider(typeof(IShape), new ShapeBinder()));
/// <br/>
/// On controller methods that need a IShape
/// public async Task<HttpResponseMessage> SomeMethod([ModelBinder] IShape shape)
/// </example>
public class ShapeBinder : IModelBinder
{
    /// <summary>Create a Shape.</summary>
    /// <returns>true if a valid shape .  false otherwise.</returns>
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
    {
        if (bindingContext.ModelType == typeof(IShape))
        {
            return CreateShape(actionContext, bindingContext);
        }

        return false;
    }

Your class heirarchy will be something like
     public abstract class Shape : IShape { .. properties for all shapes ... }
     public class SquareShape : RectangleShape { ... special case rectangle syntactic sugar that makes it a square ... }
     public class RectangleShape : Shape { ... rectangle properties }
     public class CicleShape : Shape { ... cicle properties }

and you might even some day add 
     public class CircleShape : EllipseShape { ... circle special case of ellipse properties ... }
     public class EllipseShape : Shape { ... ellipse properties ... }

Perhaps a different answer than you were thinking but you said Any suggestion and this will probably serve you well.

