How can I return an object containing a dynamic list?
I've got a working REST service in which I want to return JSON data. That works pretty well in most cases - except for one:
In that specific case I've got a List<Bla> which can contain objects of type Bla and Bla1 (which inherits from Bla).
As soon as I add a Bla1 to the list the result I get in my browser is an error.
Firefox: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://.../DoSomething. (Reason: CORS request did not succeed).
Chrome: GET https://.../DoSomething net::ERR_SPDY_PROTOCOL_ERROR
How can I return an object containing a dynamic list?
Classes
[DataContract]
public class Blibla
{
[DataMember] public bool requestSuccess;
[DataMember] List<Blubb> blubb;
[DataMember] List<Bla> blas;
public Blibla(bool success)
{
this.requestSuccess = success;
blubb = new List<Blubb>() { new Blubb(11, "einser"), new Blubb(22, "zweier"), new Blubb(33, "dreier") };
blas = new List<Bla>() { new Bla(11), new Bla1(22, 22) };
}
}
[DataContract]
public class Bla
{
[DataMember] public int id;
public Bla(int id)
{
this.id = id;
}
}
[DataContract]
public class Bla1 : Bla
{
[DataMember] public int num;
public Bla1(int id, int num) : base(id)
{
this.num = num;
}
}
[DataContract]
public class Blubb
{
[DataMember] public int ID;
[DataMember] public string name;
public Blubb(int id, string name)
{
this.ID = id;
this.name = name;
}
}
IService:
[Description("returns service's details")]
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
Blibla DoSomething();
Service:
public Blibla DoSomething()
{
Message msg;
DoHttpMethodTypeSpecific();
Blibla bb = new Blibla(true);
return bb;
}
EDIT
Abraham Qian's answer is exactly what I was looking for.
My service responds with a correctly serialized Bla1-object.
{
"__type":"Bla1",
"id":22,
"num":22
}
If someone knows of a way to suppress the automatically added "__type":"Bla1"
please let me know...