0

I'm developing an ASPNET Core WebAPI application. I will have a base model and potentially have many, many derived types of the base model. I do not want to create specialized endpoints for each of these derived types. What I would like to do is have my controller deserialize an incoming object into the base type, pass it to the service layer at which point I can determine which derived type it is and then handle it.

For example, my models might look something like this:

public class ModelA
{
  public string PropA1 { get; set; }
  public int PropA2 { get; set; }
}

public class ModelB : ModelA
{
  public string PropB1 { get; set; }
  public int PropB2 { get; set; }
}

public class ModelC : ModelA
{
  public string PropC1 { get; set; }
  public int PropC2 { get; set; }
}

Controller would be this:

  [Route("api/[controller]")]
    public class MyController : Controller
    {
        [HttpPut]
        public void Put(ModelA model)
        {
          // model could be B or C (but never A).
        }
    }

Where the "model" parameter could actually be ModelC or ModelB (or, in reality, many many others, but never the base class). I will then pass the model to a service provider which will then determine the derived type and handle it appropriately.

In addition, each of the derived types could have validation attributes (and/or implement IValidatableObject). Preferably, I would like the framework to be able to handle validation of the derived type.

Is this possible?

Jake Shakesworth
  • 3,335
  • 4
  • 29
  • 43
  • 1
    This may help: https://stackoverflow.com/questions/12638741/deserialising-json-to-derived-types-in-asp-net-web-api – Always Learning Mar 30 '18 at 23:10
  • Jake, the model bind will bind only the properties that match in you request and the action. In this case you can use composition or another class with all available parametrers and than convert to you model, checking the properties. And yes, you can use fluent validator. – Michel Borges Mar 31 '18 at 01:38
  • easiest way, but not the best use dynamic type. – fuzzybear Apr 02 '18 at 23:14

0 Answers0