I have a call to a WebAPI with the following code:
var client = new HttpClient
{
BaseAddress = new Uri("http://localhost:8490/")
};
var jObject = new JObject();
jObject.Add("paramA", paramA);
jObject.Add("paramB", paramB);
JArray jArr = JArray.FromObject(paramsGenericArr);
jObject.Add("paramC", jArr);
var content = new StringContent(jObject.ToString(), Encoding.UTF8, "application/json");
var result = await client.PostAsync("api/path/tofunc", content).ConfigureAwait(false);
result.EnsureSuccessStatusCode();
The ParamsGeneric class is an abstract type with 2 derived classes:
[DataContract]
public class ParamsTypeA : ParamsGeneric
{
[DataMember]
public long itemC {get; set;}
public ParamsTypeA() :
base()
{}
}
[DataContract]
public class ParamsTypeB : ParamsGeneric
{
[DataMember]
public long itemD {get; set;}
public ParamsTypeB() :
base()
{}
}
[DataContract]
[KnownType(typeof(ParamsTypeA))]
[KnownType(typeof(ParamsTypeB))]
public abstract class ParamsGeneric
{
[DataMember]
public long itemA { get; set; }
[DataMember]
public long itemB {get; set;}
public ParamsGeneric()
{}
}
I suspect that I have a problem with the deserialization in the WebAPI:
public class ClientData
{
public string paramA { get; set; }
public string paramB { get; set; }
public ParamsGeneric[] paramC { get; set; }
}
[HttpPost]
[Route("api/path/tofunc")]
public async Task<bool> DoStuffAsync(ClientData clientData)
{
....
}
I have a problem with the paramsGenericArr
/paramC
(which is of type ParamsGeneric[]
, and holds items of type ParamsTypeA
& ParamsTypeB
)
The WebAPI receives a blank array (ParamsGeneric[0]
), along with the other parameters.
Help will be appriciated.
UPDATE
Even if I try to pass a single ParamsGeneric
object instead of an array, I receive null
instead of the object.
SOLUTION
var serializer = new JsonSerializer();
serializer.TypeNameHandling = TypeNameHandling.Auto;
JArray jArr = JArray.FromObject(paramsGenericArr, serializer);
Did the trick.