I have a scenario where I'm passing some data to an ASP.NET Web API method, one piece of which is a list of objects which share a base type. So, the method accepts the POST data in a single DTO parameter, as Web API expects, like so:
public HttpResponseMessage SaveConfig(SaveConfigRequest req) {
// do stuff with req
}
The SaveConfigRequest
DTO has data something like this:
public class SaveConfigRequest {
public string Code { get; set; }
public IEnumerable<BaseParameter> Parameters { get; set; }
}
BaseParameter
is an abstract class with a couple of concrete implementations:
public abstract class BaseParameter {
protected BaseParameter(ParameterType type) {
this.Type = type;
}
public ParameterType Type { get; private set; }
public string Name { get; set; }
}
// TODO: implement other parameters
public class DateParameter : BaseParameter {
public DateParameter() : base(ParameterType.Date) {}
public string DefaultDateFormula { get; set; }
}
What I need is for Web API to be able to deserialize a POST request containing a collection of parameters, so that they're deserialized into their concrete types. I'm POSTing the data serialized as JSON.
One attempt that I've made is to set the TypeNameHandling
of the Json.NET formatter to Auto
and adding a $type
property in the JSON that I'm sending, but that still results in an empty collection in the method.
A second attempt has been to create a custom model binder for the BaseParameter
type, but I think it's not getting triggered because BaseParameter
isn't the model, just a part of it. Perhaps I haven't configured it correctly (I've tried a ModelBinder
attribute on BaseParameter
and calling configuration.BindParameter(typeof(BaseParameter), new ParameterModelBinder())
in App_Start
).
So, my question is what is the most straightforward way to allow part of my Web API method's model parameter to accept a collection of values of an abstract type?