How to return a List<object> in WCF

房东的猫 提交于 2019-11-29 13:16:24

You could define

[KnownType(typeof(MyChildObject0))]
...
[KnownType(typeof(MyChildObjectM))]
public class MyBaseObject { ... }

public class MyChildObject0 : MyBaseObject { ... }
...
public class MyChildObjectM : MyBaseObject { ... }

Or you could add the attribute only once and define static method that returns all M+1 types at once.

and modify:

public class WrapHome
{
  ...
  public List<MyBaseObject> CHART { get;set; }
}

In my case the solution is more simple.

I have a class that I return in all my mehotds, like this:

[DataContract]
public class Result
    {

        [DataMember]
        public string KeyMensaje;
        [DataMember]
        public string ErrorMessage;        
        [DataMember]        
        public object Objeto;

        ...
   }

The problem is due to Objeto object inside this class. This object is used to return variables types and it can't be serialized if is a complex object, for example:

res = new Result(list, "ok", "", "", "", null);  
return res;

In this case object (list) is a list of other custom object, for example List<CustomEmployee>

The solution is add on top Result class the complex types that object can be, like this:

[DataContract]
[KnownType(typeof(List<CustomEmployee>))]
[KnownType(typeof(CustomEmployee))]
public class Result
{
   ...
}

To make it work, your service has to know the types it needs to serialize. If they cannot be found out by looking at your method's signature (for example because one type is object), you need to list all types that could possibly be in that object.

Annotate them to the top of your service class, if you list for example can have instances of foo, bar and baz:

[ServiceKnownType(typeof(foo))]
[ServiceKnownType(typeof(bar))]
[ServiceKnownType(typeof(baz))]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!