简体   繁体   中英

WCF REST JSON return dynamic list

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...

According to your error and code, I have made a test and found that there is a serialization problem in the Bla class. When transferring the Bla class, WCF could not recognize the subclass(Bla1) and how to serialize them, So we should add the KnowType attribute to the base class.

[DataContract]
[KnownType(typeof(Bla1))]
public class Bla
{
    [DataMember] public int id;
    public Bla(int id)
    {
        this.id = id;
    }
}

https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/data-contract-known-types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM