Sorry if this has been asked an answered a million times already, but I can't seem to find a solution on Google or SO.
In ASP.NET Core, is it possible to write a custom model binder or some such, that will allow me to have some inheritance support in a web API?
Basically I have a class like:
public class Order {
public Guid Id { get; set; }
public PaymentContainer PaymentParameters { get; set; }
}
And a container class like
public class PaymentContainer
{
public string Type { get; set; }
public IPaymentParameters Value { get; set; }
}
And some classes that implement the IPaymentParameters interface, and a controller method such as:
[HttpPost]
public IActionResult CreateOrder([FromBody]Order order)
{
}
I would very much like the client to be able to send in json such as:
{
"id" : "1234-..-1234",
"paymentParameters" : {
"type": "SpecialParameters1",
"value" : { /* instance of specialparameters1 here */ }
}
}
And then have the "value" property be an instance of "SpecialParameters1" once it arrives in the controller method.
I would think it is possible to write a modelbinder, but i can't quite wrap my head around how it would be done.
Note: I am aware of the approach where one can change the Json.Net TypeNameHandling, but I would rather NOT mess with all the other stuff that relies on the json serializer, and just setting it to Auto or All will open up some avenues for remote code execution.
Clarification: A small update after the first answer The goal is to have multiple instance of the parameters, such that the following input also "works"
{
"id" : "1234-..-1234",
"paymentParameters" : {
"type": "SpecialParameters2",
"value" : { /* instance of specialparameters2 here */ }
}
}
And of course I would have classes
public class SpecialParameters1 : IPaymentParameters{}
public class SpecialParameters2 : IPaymentParameters{}