简体   繁体   中英

How to return multiple types of objects array from Json Format WCF service?

I have a wcf application that helps mobile to sync. However, I could now return multiple type of objects from one single method.

What I did was create a object call sync objects and add all objects to the sync objects array and then serialise it. The following would show the class.

[DataContract]
    public class CSyncObjects
    {
        [DataMember]
        public string DataType { get; set; }
        [DataMember]
        public object DataObject { get; set; }

        public CSyncObjects(string Type, object Object)
        {
            this.DataType = Type;
            this.DataObject = Object;
        }
    }

However, whenever I try to access it by url I get the following error ERR_CONNECTION_RESET error on Chrome. What should I do?

You could create a tuple, to return multiple stuff in the same method.

Tuple<int, string, bool> tuple = new Tuple<int, string, bool>(1, "dog", true);
return tuple;

Passing an instance of type system.object across the service boundary is both nonsensical and breaks tenet one of SOA: Boundaries are explicit .

If you need to be able to pass multiple types, then WCF provides the ServiceKnownType attribute , which gives you a way to treat instances of multiple types polymorphically over the service boundary.

Simply create a base class to represent the operation argument, and then decorate the service interface definition with the supported derived types via ServiceKnownType attribute:

[ServiceContract]
[ServiceKnownType(typeof(RoadBike))]
[ServiceKnownType(typeof(AllTerrianBike))]
public Interface IBikeStoreFront
{
     [OperationContract]
     Bicycle GetBike(int bikeId);

     [OperationContract]
     void UpdateBike(Bicycle bike);  
} 

[DataContract]
public class Bicycle 
{
}

[DataContract]
public class RoadBike : Bicycle
{
}

[DataContract]
public class AllTerrianBike : Bicycle
{
}

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